Last active
December 28, 2015 20:19
-
-
Save att14/7556310 to your computer and use it in GitHub Desktop.
Don't do this.
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 collections import namedtuple | |
| from new import instancemethod | |
| def to_object(name, dictionary, base_class=object, functions=None, properties=None): | |
| functions = functions or {} | |
| properties = properties or {} | |
| class Object(base_class): | |
| __name__ = name | |
| def __getattr__(self, attr): | |
| try: | |
| return properties[attr](self) | |
| except KeyError: | |
| return dictionary[attr] | |
| obj = Object() | |
| for function_name, function in functions.iteritems(): | |
| setattr(obj, function_name, instancemethod(function, obj, type(obj))) | |
| return obj | |
| def objectify_kwargs(func): | |
| def inner(*args, **kwargs): | |
| args = args + (to_object('ExtraArgs', kwargs), ) | |
| return func(*args) | |
| return inner | |
| if __name__ == '__main__': | |
| assert to_object('NewObject', {'foo': 'bar'}).foo == 'bar' | |
| assert to_object('NewObject', {'foo': True, 'bar': False}, functions={'foo': lambda self: True}).foo() | |
| assert to_object('NewObject', {'foo': True, 'bar': False}, properties={'is_foobar': lambda self: self.foo and self.bar}).is_foobar == False | |
| @objectify_kwargs | |
| def function(arg1, arg2, rest): | |
| assert rest.foo == 'bar' | |
| function('a', 'b', foo='bar') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment