Question

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

Was it helpful?

Solution

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).

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top