Why are default arguments in function signatures executed when loading a module?
Example test.py
:
import os
def environment_key(key=os.environ["MY_ENV_KEY"]):
print(key)
When I load on the test.py
on cmd line python -m test.py
I get following error:
bash-4.2# python -m test.py
Traceback (most recent call last):
File "/usr/lib64/python2.7/runpy.py", line 163, in _run_module_as_main
mod_name, _Error)
File "/usr/lib64/python2.7/runpy.py", line 102, in _get_module_details
loader = get_loader(mod_name)
File "/usr/lib64/python2.7/pkgutil.py", line 462, in get_loader
return find_loader(fullname)
File "/usr/lib64/python2.7/pkgutil.py", line 472, in find_loader
for importer in iter_importers(fullname):
File "/usr/lib64/python2.7/pkgutil.py", line 428, in iter_importers
__import__(pkg)
File "test.py", line 4, in <module>
def environment_key(key=os.environ["MY_ENV_KEY"]):
File "/usr/lib64/python2.7/UserDict.py", line 40, in __getitem__
raise KeyError(key)
KeyError: 'MY_ENV_KEY'
I far as i can imagine, Python tries to initialise the default arguments at module load time. Can i prevent (lazy load) this behavior?
Thx