Skip to content

Commit 1b4b2bf

Browse files
committed
adding CrazyLocals for importing stuff automatically
So, this is a really bad idea. This makes names from sys.modules magically available without needing to import them. It does that by replacing the locals dict by a dict subclass that looks up names in sys.modules when they're not present in current locals. Please do NOT merge! But have fun. :)
1 parent b30efb8 commit 1b4b2bf

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

bpython/curtsiesfrontend/interpreter.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,21 @@ def format(self, tokensource, outfile):
6161
outfile.write(parse(o.rstrip()))
6262

6363

64+
class CrazyLocals(dict):
65+
def __getitem__(self, name):
66+
try:
67+
return super(CrazyLocals, self).__getitem__(name)
68+
except KeyError:
69+
import sys
70+
try:
71+
return sys.modules[name]
72+
except KeyError:
73+
for mod in sys.modules.values():
74+
if hasattr(mod, name):
75+
return getattr(mod, name)
76+
raise
77+
78+
6479
class Interp(ReplInterpreter):
6580
def __init__(self, locals=None, encoding=None):
6681
"""Constructor.
@@ -75,6 +90,9 @@ def __init__(self, locals=None, encoding=None):
7590
"""
7691
if locals is None:
7792
locals = {"__name__": "__console__", "__doc__": None}
93+
94+
locals = CrazyLocals(locals)
95+
7896
if encoding is None:
7997
encoding = getpreferredencoding()
8098
ReplInterpreter.__init__(self, locals, encoding)

0 commit comments

Comments
 (0)