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() |
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 whetherthing
is theos
module 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)=True
foo
andbar
are bothos
at first.Inside
no_global
, the import overwritesfoo
to besys
, but once the function exits and the overwrittenfoo
goes out of scope,foo
in the module scope isos
again.Inside
with_global
, though, the import overwrites the module-scopefoo
. Module-scopefoo
is then checked insidewith_global
and found to besys
, and then checked again outsidewith_global
and found to besys
there also.