-3

I noticed the following behavior in Python:

>>> class foo:
...     def __init__(self, x=0):
...             self.x = x
...     def bar(self):
...             self.x = self.x + 1
... 
>>> def f(a=foo()):
...     a.bar()
...     return a
... 
>>> c = f()
>>> c.x
1
>>> d = f()
>>> d.x
2
>>> d == c
True

It is as if the variable a became global, which is not true but still calling the method f the variable a does not re-instantiate as I expected.

What is the reason behind this?

martineau
  • 119,623
  • 25
  • 170
  • 301
David
  • 119
  • 4
  • It is a design decision of Python that this is only processed once when the function definition of "f" is processed, not on each call. – Michael Butscher Mar 23 '20 at 18:00

3 Answers3

0

a=foo() will only ever get evaluated one time, once the module is loaded. It will not get run again when you call the function. Default arguments for functions always behave this way.

ruohola
  • 21,987
  • 6
  • 62
  • 97
0

The default values of function arguments are evaluated at the time of the function's definition, not when the function is called.

blhsing
  • 91,368
  • 6
  • 71
  • 106
0

Default values are evaluated and stored at the time the function is defined.

>>> f.__defaults__
(<__main__.foo object at 0x105c02860>,)

The expression foo() isn't stored as the default, to be called later; the result of evaluating the expression is.

The parameter a is still a local variable, but it references an object that is shared by all invocations of f if no argument is passed to the call.

chepner
  • 497,756
  • 71
  • 530
  • 681