Skip to content

Instantly share code, notes, and snippets.

@ParitoshSingh07
Last active August 27, 2021 15:50
Show Gist options
  • Save ParitoshSingh07/932272403f1a9e94ad5e1b9e16d23346 to your computer and use it in GitHub Desktop.
Save ParitoshSingh07/932272403f1a9e94ad5e1b9e16d23346 to your computer and use it in GitHub Desktop.
funky imports
# x.py
print("x begin")
if __name__ == "__main__":
import sys
from collections import UserDict
class DictWatch(UserDict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __getitem__(self, key):
val = super().__getitem__(key)
print('FETCHING EXISTING ITEM FROM CACHE', key)
return val
def __setitem__(self, key, val):
print('OH, A NEW IMPORT. IMPORT AND RUN, ADD TO CACHE', key)
super().__setitem__(key, val)
print("let me just hijack some stuff")
sys.modules = DictWatch(**sys.modules)
print("x begin part deux")
import y
print("x end")
# y.py
print("y begin")
import x
print("y end")
#### abcd.py
if __name__ == "__main__":
import sys
from collections import UserDict
class DictWatch(UserDict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __getitem__(self, key):
val = super().__getitem__(key)
print('FETCHING EXISTING ITEM FROM CACHE', key)
return val
def __setitem__(self, key, val):
print('OH, A NEW IMPORT. IMPORT AND RUN, ADD TO CACHE', key)
super().__setitem__(key, val)
print("let me just hijack some stuff")
sys.modules = DictWatch(**sys.modules)
import x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment