Created
January 4, 2016 01:35
-
-
Save benburrill/ce2c5ef5677c36542df8 to your computer and use it in GitHub Desktop.
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
# Here we create a metaclass that effectively turns a class scope into a different programming environment where setting variables under one name saves them to another | |
# This level of madness requires Python 3 to run. | |
class CrazyDict(dict): | |
def __setitem__(self, item, value): | |
super().__setitem__("potato_" + str(item), value) | |
class CrazyMeta(type): | |
def __prepare__(*args, **kwargs): | |
return CrazyDict() | |
if __name__ == "__main__": | |
class Example(metaclass=CrazyMeta): | |
some_var = "hello, world" # let's set a variable! | |
try: print(some_var) # your normal laws of sanity do not work here | |
except NameError: # I can't even use 'as' here | |
print("POTATO ERROR!!!") | |
print(potato_some_var) # ah, here it is | |
potato_some_var += "!" # add an exclamation mark to the end | |
print(potato_some_var) # unmodified? | |
print(potato_potato_some_var) # oh, of course... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment