Sat 22 Apr 2006
While playing around with some metaprogramming stuff for the next version of typecheck, I discovered this:
>>> def foo(a=5): ... return a ... >>> foo() 5 >>> foo.func_defaults = (6,) >>> foo() 6
This isn’t limited to change a keyword parameter’s default value, either:
>>> def foo(a, b): ... return a, b ... >>> foo.func_defaults = (4, 5) >>> foo() (4, 5)
Similarly, you can use this to turn keyword parameters into positional parameters:
>>> def foo(a, b=5): ... return a, b ... >>> foo.func_defaults = () >>> foo() Traceback (most recent call last): ... TypeError: foo() takes exactly 2 arguments (0 given)
Alright, this isn’t so much a “trick”, given that func_defaults is listed as writeable in the docs, but it’s still neat.