Вопрос

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

Это было полезно?

Решение

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

Другие советы

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top