-
Notifications
You must be signed in to change notification settings - Fork 0
/
globalize.py
106 lines (77 loc) · 2.16 KB
/
globalize.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import builtins
import importlib
import sys
# __globals__ = __builtins__.globals
# __globals__ = globals()
def get_or_import(dct, name):
print(f"*** getting {name}")
try:
return dct[name]
except KeyError:
print(f"*** missing {name}")
try:
module = importlib.import_module(name)
except ImportError:
print(f"*** failed to import {name}")
raise AttributeError(name)
else:
print(f"*** successfully imported {name}")
dct[name] = module
print(f"*** returning {name}")
return module
class Base:
def __init__(self, dct):
self._dct = dct
def __getattr__(self, name):
return get_or_import(self._dct, name)
base = Base(globals())
class ImportDict(dict):
def __missing__(self, name):
print(f"*** missing {name}")
try:
module = importlib.import_module(name)
except ImportError:
print(f"*** failed to import {name}")
raise KeyError(name)
print(f"*** successfully imported {name}")
self[name] = module
print(f"*** returning {name}")
return module
# # def globals():
# # print('*** accessing globals')
# # return ImportDict(__globals__)
# builtins.__globals__ = builtins.globals()
assert (
globals
is builtins.globals
is __builtins__['globals']
)
assert (
globals()
is builtins.globals()
is __builtins__['globals']()
)
builtins.__globals__ = globals()
assert (
__globals__ # noqa
is globals()
is builtins.globals()
is builtins.__globals__
is __builtins__['globals']()
is __builtins__['__globals__']
)
importer = ImportDict(globals())
builtins.globals = lambda: importer
assert globals() is not __globals__ # noqa
assert globals() is importer
# __builtins__ = importer
class Test(type(builtins)):
def __getattr__(self, name):
print(f"*** getting {name}")
try:
return importer[name]
except KeyError:
print(f"*** failed to get {name}")
raise AttributeError(name)
sys.modules['builtins'] = Test('builtins')
# print(atomic)