Re:Python quirks
by adamtj on Friday July 12, 2013 @10:40PM
(#6036477)
It is perhaps more correct to say "when the function is instantiated". Functions in python aren't exactly "defined". Functions are objects same as everything else. The "def" keyword is how you call the constructor for a function object. The kwarg default values are evaluated once at object construction time and saved.
The "def" statement may construct different distinct function objects from a single definition. Each distinct function object has different default value objects, but each function object reuses its own default value objects each time it's called.
Consider this:
def outer_fn():
def inner_fn(foo={}):
# The id() function returns an internal
# object identifier. Different objects
# have different ids.
print id(foo)
return inner_fn
inner_fn_1 = outer_fn()
inner_fn_2 = outer_fn()
inner_fn_1()
inner_fn_1()
inner_fn_2()
inner_fn_2()
The "def" statement may construct different distinct function objects from a single definition. Each distinct function object has different default value objects, but each function object reuses its own default value objects each time it's called.
Consider this: