Question

How do I get the mutable default arguments tuple in Python 3?

def foo(x=[]):
    pass

Failed Attempt:

foo.func_defaults

Error:

AttributeError: 'function' object has no attribute 'func_defaults'
Was it helpful?

Solution

You should be using __defaults__, like this

def foo(x=[]):
    x.append(1)

foo()
foo()
print(foo.__defaults__)
# ([1, 1],)

Quoting from the data model,

__defaults__

A tuple containing default argument values for those arguments that have defaults, or None if no arguments have a default value.

It means that, when you have a function which doesn't have a default parameter, then __defaults__ will be None

def foo():
    pass

print(foo.__defaults__)
# None
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top