Last active
February 6, 2018 22:19
-
-
Save dev-dull/bc9ee3b5d1991b99a6d2a7c843da8c70 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 itertools import cycle | |
| #### I wrote this to use with flask to have a state-aware backend storage | |
| #### Turns out flask already has this: http://flask.pocoo.org/docs/0.12/appcontext/ | |
| class o(dict): | |
| hi='' | |
| def __init__(self, env): | |
| self.env = env | |
| def pp(self): | |
| print(self.env) | |
| class foo(dict): | |
| def __init__(self): | |
| self.__dict__['__c'] = cycle(['one', 'two', 'tweee']) | |
| self.__dict__['env'] = '' | |
| self.__dict__['a_bool'] = True | |
| def __getitem__(self, key): | |
| self._set_env() | |
| return super().__getitem__(self.__dict__['env'])[key] | |
| def __setitem__(self, key, value): | |
| self._set_env() | |
| super().__getitem__(self.__dict__['env'])[key] = value | |
| def __getattr__(self, key): | |
| self._set_env() | |
| return getattr(super().__getitem__(self.__dict__['env']), key) | |
| def __setattr__(self, key, value): | |
| self._set_env() | |
| if key == 'a_bool': | |
| self.__dict__['a_bool'] = value | |
| else: | |
| setattr(super().__getitem__(self.__dict__['env']), key, value) | |
| def _set_env(self): | |
| self.__dict__['env'] = next(self.__dict__['__c']) # emulate grabbing a GET pramater from a URL | |
| if self.__dict__['env'] not in self: | |
| super().__setitem__(self.__dict__['env'], o(self.__dict__['env'])) | |
| bar = foo() | |
| bar.hi = 'bye' | |
| bar.hi = 'hola' | |
| bar.hi = 'cheese' | |
| print(bar.hi) | |
| print(bar.hi) | |
| print(bar.hi) | |
| print(bar.env) | |
| bar.pp() | |
| bar.pp() | |
| bar.pp() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment