1

I just was messing around in Python and I made a function called f. I gave it a keyword/named argument with a default value initialized by some variable:

>>> test = "first"
>>>
>>> def f(test_arg=test):
...    print(test_arg)
>>>
>>> f()
first
>>> test = "second"
>>> f()
first

I changed that variable's contents, but the argument's default value did not update.

How can I change the value of the default argument?

Michel de Ruiter
  • 7,131
  • 5
  • 49
  • 74
Wouterr
  • 516
  • 7
  • 16
  • 2
    Python variables are *references to objects*. You set the default value for `test_arg` to point to the same object that `test` pointed to. Setting `test` to point to another object does not alter other references to the previous referent. – Martijn Pieters Mar 19 '19 at 19:18
  • See https://nedbatchelder.com/text/names.html for a very good treatise on the Python model. – Martijn Pieters Mar 19 '19 at 19:19
  • It sounds like the deeper issue might be an expectation that the argument default is an expression rather than an object. While almost every language with default argument values implements them as expressions evaluated on each call, Python is an exception, storing a reference to a specific object that will be used as the default. – user2357112 Mar 19 '19 at 19:26
  • I don't want to update an outer variable. Just the keyword. – Wouterr Mar 19 '19 at 19:31
  • That sounds like you should either be using `f("second")`, or be using function attributes instead of arguments. – user2357112 Mar 19 '19 at 20:05

0 Answers0