1
def foo(a, bar=[]):
    bar.append(a)
    print(bar)

foo(1)  # [1]
foo(1)  # [1, 1]
foo(1)  # [1, 1, 1]

Reasons and possible uses for such behavior would be welcome. Thanks.

Vikas Tikoo
  • 1,545
  • 11
  • 14
  • That's not a keyword argument. Using `=` in a function definition has nothing to do with keyword arguments. That's a default argument value. – user2357112 Dec 22 '16 at 22:10
  • As for why it works that way, probably implementation convenience way back in the days of 1.whatever or earlier, when it was implemented. It would have been more complicated (but probably worthwhile) to do it differently. – user2357112 Dec 22 '16 at 22:11
  • @user2357112 per the duplicate there are some reasonable arguments for the current implementation, not just whatever was easiest! – jonrsharpe Dec 22 '16 at 22:14
  • 2
    Here is n example of why you might want this functionality, although it is not very detailed: http://docs.python-guide.org/en/latest/writing/gotchas/#when-the-gotcha-isn-t-a-gotcha – elethan Dec 22 '16 at 22:25
  • @jonrsharpe: Those have always felt like rationalizations to me. If we were introducing default arguments now, without the weight of past design choices on us, the design that would be the most useful for the use case of "I want this argument to default to this thing" would be to evaluate the default argument value at function execution time. – user2357112 Dec 22 '16 at 23:14
  • @user2357112 unless you changed the definition of default values to be callables that return the actual value (so this would be `def foo(a, bar=list):`, similar to the way you work with e.g. `defaultdict`) I don't see how you could implement that in a way that is consistent with the way the rest of Python works. As a rhetorical example, how would things like signature introspection work? – jonrsharpe Dec 22 '16 at 23:22
  • @jonrsharpe: Default values don't need to be part of the signature. It's fine if default value introspection comes down to `inspect.getsource` and/or bytecode parsing. After all, that's already the only way you can introspect the function's body, and default assignments would essentially be a header before the function body with an evaluate-on-call design. – user2357112 Dec 22 '16 at 23:27

0 Answers0