-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcustom_finder.py
45 lines (31 loc) · 949 Bytes
/
custom_finder.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
import sys
from importlib.machinery import ModuleSpec
import importlib.abc
class CustomModule:
pass
class CustomFinder:
def find_spec(self, name, path=None, target=None):
print('Finding', name, path, target)
if name == 'mymod':
return ModuleSpec(name, CustomLoader())
class CustomLoader:
def create_module(self, name):
print('Creating', name)
return CustomModule()
def exec_module(self, mod):
print(vars(mod))
print('Executing', mod)
sys.meta_path.insert(0, CustomFinder())
import mymod
print(mymod)
class CustomImporter(importlib.abc.InspectLoader):
def find_spec(self, name, path=None, target=None):
print('Finding', name, path, target)
if name == 'zzmod':
return ModuleSpec(name, self)
def get_source(self, name):
return 'p = 3'
sys.meta_path.insert(0, CustomImporter())
import zzmod
print(zzmod)
print(zzmod.p)