-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimport_overload.py
58 lines (36 loc) · 965 Bytes
/
import_overload.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# import_overload.py
import builtins
import importlib
old_imp = builtins.__import__
def my_import(*args, **kwargs):
if args[0] == "foo":
return "Foo me"
else:
return old_imp(*args, **kwargs)
builtins.__import__ = my_import
import foo
#print(type(foo))
import sys
class Finder(object):
def find_module(self, fullname, path=None):
if fullname == "bar":
return Loader()
return None
class Loader(object):
def load_module(self, fullname):
if fullname in sys.modules:
return sys.modules[fullname]
spec = importlib.machinery.ModuleSpec(fullname, None)
mod = importlib.util.module_from_spec(spec)
mod.__loader__ = self
sys.modules[fullname] = mod
mod.__file__ = "Naw"
code = "print('bar you')\nx=5"
exec(code, mod.__dict__)
return mod
def create_module(self, spec):
return None
sys.meta_path = [Finder()]
import os
import bar
print(bar.x)