Created
August 1, 2020 17:00
-
-
Save tilalis/aac26741c21056216a0e56b155d136c6 to your computer and use it in GitHub Desktop.
It's weird, but it works! python: moduleclass
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__bases__ = (dict, ) | |
def __missing__(self, key): | |
self[key] = key | |
return key |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from moduleclass import moduleclass | |
with moduleclass: | |
import betterdict | |
d = betterdict() | |
print(d['key']) # prints 'key' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import types | |
import builtins | |
from importlib import __import__ | |
from contextlib import contextmanager | |
def _moduleclass_import(name, *args, **kwargs): | |
module = __import__(name, *args, **kwargs) | |
metaclass = getattr(module, '__metaclass__', type) | |
bases = getattr(module, '__bases__', ()) | |
moduleclass = metaclass(name, bases, { | |
key: value | |
for key, value in module.__dict__.items() | |
if key not in { | |
'__name__', '__dict__', '__loader__', '__builtins__', '__build_class__', '__package__', '__spec__' | |
} and not isinstance(value, types.ModuleType) | |
}) | |
return moduleclass | |
@contextmanager | |
def _moduleclass(): | |
builtins.__import__ = _moduleclass_import | |
yield | |
builtins.__import__ = __import__ | |
moduleclass = _moduleclass() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment