Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get mutable default arguments of func

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'
like image 985
Phoenix Avatar asked Feb 04 '26 02:02

Phoenix


1 Answers

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
like image 146
thefourtheye Avatar answered Feb 05 '26 15:02

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!