Evaluation of Default Arguments in Python
Today I stumbled upon a very subtle problem with default arguments in python. I noticed that loading a python module already instantiated one of my classes even though I could not find an installation of this class. In the end it turned out to be a default argument for a function:
def foo(arg=MyClass()): pass
As I am currently programming a lot in C++ this did not look suspicious to me. But from python’s point of view it absolutely makes sense that the default value for arg is already constructed at module load time and not only on a call to that functions. Moreover it is important to remember that this default argument is constructed only once for all calls to a function as stated here.
2011-01-19 00:00 (Last updated: 2021-04-30 20:40)