Created
January 12, 2025 04:18
-
-
Save bskinn/7e5f8ba50109f6bbfbf0b6e642c0040b to your computer and use it in GitHub Desktop.
Demonstration of 'import stomping' behavior of imports inside functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os as foo | |
| import os as bar | |
| print() | |
| print(f"Initial {'rmdir' in dir(foo)=}") | |
| print(f"Initial {'rmdir' in dir(bar)=}") | |
| print() | |
| def no_global(): | |
| import sys as foo | |
| print(f"Inside no_global {'rmdir' in dir(foo)=}") | |
| print(f"Inside no_global {'rmdir' in dir(bar)=}") | |
| no_global() | |
| print() | |
| print(f"After no_global() {'rmdir' in dir(foo)=}") | |
| print(f"After no_global() {'rmdir' in dir(bar)=}") | |
| print() | |
| def with_global(): | |
| global foo | |
| import sys as foo | |
| print(f"Inside with_global {'rmdir' in dir(foo)=}") | |
| print(f"Inside with_global {'rmdir' in dir(bar)=}") | |
| with_global() | |
| print() | |
| print(f"After with_global() {'rmdir' in dir(foo)=}") | |
| print(f"After with_global() {'rmdir' in dir(bar)=}") | |
| print() |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We print
'rmdir' in dir(thing)as a probe for whetherthingis theosmodule or not. If the test yieldsTrue, then it'sos.Output on Windows Python 3.12.8:
>python import_stomp.py Initial 'rmdir' in dir(foo)=True Initial 'rmdir' in dir(bar)=True Inside no_global 'rmdir' in dir(foo)=False Inside no_global 'rmdir' in dir(bar)=True After no_global() 'rmdir' in dir(foo)=True After no_global() 'rmdir' in dir(bar)=True Inside with_global 'rmdir' in dir(foo)=False Inside with_global 'rmdir' in dir(bar)=True After with_global() 'rmdir' in dir(foo)=False After with_global() 'rmdir' in dir(bar)=Truefooandbarare bothosat first.Inside
no_global, the import overwritesfooto besys, but once the function exits and the overwrittenfoogoes out of scope,fooin the module scope isosagain.Inside
with_global, though, the import overwrites the module-scopefoo. Module-scopefoois then checked insidewith_globaland found to besys, and then checked again outsidewith_globaland found to besysthere also.