-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautoimport.py
More file actions
74 lines (57 loc) · 2.05 KB
/
autoimport.py
File metadata and controls
74 lines (57 loc) · 2.05 KB
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
"""Don't try this at home."""
from subprocess import run
from importlib import import_module
def autoimport(name, otherwise=Exception):
print(f"Couldn't find {name}. You probably just forgot to import it!")
try:
obj = import_module(name)
except ModuleNotFoundError:
print(f"Hm, don't see any modules named '{name}'.")
print(f"You must have forgotten to install it! Let's fix that...")
try:
run(['pip', 'install', name], check=True)
obj = import_module(name)
except Exception:
print(f"Aw, that didn't work :( Sorry!")
raise otherwise
print(f"Found it! Here you go: {obj}")
return obj
class AutoImportDict(dict):
def __missing__(self, key):
if not isinstance(key, str) or key.startswith('_'):
raise KeyError(key)
try:
return globals()[key]
except KeyError:
pass
try:
return getattr(__builtins__, key)
except AttributeError:
pass
return autoimport(key, KeyError(key))
class AutoImportMeta(type):
def __prepare__(meta, *args, **kwargs):
return AutoImportDict()
def __getattr__(self, name):
return autoimport(name, AttributeError(name))
class _(metaclass=AutoImportMeta):
if sys.argv[1:2] != ['--i-understand-the-consequences-of-my-actions']:
var = os.environ.get('I_UNDERSTAND_THE_CONSEQUENCES_OF_MY_ACTIONS')
try:
understood = ast.literal_eval(var)
except Exception:
understood = False
if not understood:
exit("You don't understand the consequences of your actions.")
if __name__ == '__main__':
url = (
'https://'
'raw.githubusercontent.com'
'/doctaphred/emojencode/master/LICENSE'
)
class packages(metaclass=AutoImportMeta):
print(requests.get(url).text)
expected = '😘😗😥😹😈😆😱😭😘😖😼💩'
result = packages.emojencode.e64encode(b'ayy lmao')
print(result)
assert expected == result