Skip to content

Instantly share code, notes, and snippets.

@rshk
Last active March 7, 2016 11:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rshk/a92623030d3fc13afc21 to your computer and use it in GitHub Desktop.
Save rshk/a92623030d3fc13afc21 to your computer and use it in GitHub Desktop.
In [1]: from schema_object import SchemaObject
In [2]: class Person(SchemaObject):
...: first_name = None
...: last_name = None
...: email = None
...:
In [3]: Person()
Out[3]: Person()
In [4]: Person(first_name='Foo', last_name='Bar')
Out[4]: Person(first_name='Foo', last_name='Bar')
In [5]: Person(invalid='something')
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-5-70a7a2cc4ef9> in <module>()
----> 1 Person(invalid='something')
/tmp/tmp.TbiZ1MuzjJ/schema_object.py in __init__(self, **attrs)
3 def __init__(self, **attrs):
4 for key, val in attrs.items():
----> 5 setattr(self, key, val)
6
7 def __setattr__(self, name, value):
/tmp/tmp.TbiZ1MuzjJ/schema_object.py in __setattr__(self, name, value)
6
7 def __setattr__(self, name, value):
----> 8 getattr(self, name) # raise AttributeError if not set
9 super().__setattr__(name, value)
10
AttributeError: 'Person' object has no attribute 'invalid'
class SchemaObject:
def __init__(self, **attrs):
for key, val in attrs.items():
setattr(self, key, val)
def __setattr__(self, name, value):
getattr(self, name) # raise AttributeError if not set
super().__setattr__(name, value)
def __repr__(self):
myname = self.__class__.__name__
args = ', '.join('{}={}'.format(key, repr(value))
for key, value in self.__dict__.items())
return '{}({})'.format(myname, args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment