Skip to content

Instantly share code, notes, and snippets.

@ncoghlan
Last active December 19, 2015 03:38
Show Gist options
  • Save ncoghlan/5891123 to your computer and use it in GitHub Desktop.
Save ncoghlan/5891123 to your computer and use it in GitHub Desktop.
Python namespaces with side effects
>>> class Madness(dict):
... def __setitem__(self, attr, value):
... if isinstance(value, type):
... value.__name__ = attr
... dict.__setitem__(self, attr, value)
...
>>> code = """\
... class Example(object): pass
... NewName = Example
... print(Example.__name__)
... """
>>> exec code in Madness()
NewName
>>> class Madness(dict):
... def __setitem__(self, attr, value):
... if isinstance(value, type):
... value.__name__ = attr
... dict.__setitem__(self, attr, value)
...
>>> code = """\
... class Example: pass
... NewName = Example
... print(Example.__name__)
... """
>>> exec(code, Madness())
NewName
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment