2

When I try the following I get an error

def test_func(key1=2.7, key2=key1*3.5):
    print(key1, key2)

NameError: name 'key1' is not defined

My solution would be something like

def test_func(key1=2.7, key2=None):
    if not key2:
        key2 = key1*3.5

    print(key1, key2)

but this looks kind of ugly to me. Does anybody have a better solution?

edit:

so my final solution is

def test_func(key1=2.7, key2=None):
    if key2 is not None:
        key2 = key1*3.5

    print(key1, key2)

thanks for all answers

Peter
  • 33
  • 5
  • maybe you should even change that to an explicit `is key2 is not None`, otherwise users will be unable to pass `0` as the second argument. – Niklas B. Feb 24 '13 at 11:05
  • the numbers were just an example, the function i use looks quite different, but you are right. i did not think on that. – Peter Feb 24 '13 at 11:12

2 Answers2

5

Nope, there is no better solution.

Function argument definitions can be expressions, but they are evaluated only once (which sometimes surprises people, see "Least Astonishment" and the Mutable Default Argument).

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

My solution would be:

def t(key1=1, **kwargs):
    key2 = kwargs.get('key2', key1*2.7)

getting key2 from kwargs and get data from it with the default key1*2.7

Julian Hille
  • 669
  • 5
  • 11
  • That has the disadvantage that the user will not get an error if he passes an unexpected parameter, like `key3`. It will just silently ignore it. – Niklas B. Feb 24 '13 at 11:28