Merge pull request #286 from Globegitter/easier-private-state

Allow initialising ObjectType with private state.
This commit is contained in:
Syrus Akbary 2016-09-12 08:09:31 -07:00 committed by GitHub
commit 2fbf17a109
2 changed files with 15 additions and 1 deletions

View File

@ -95,7 +95,7 @@ class ObjectType(six.with_metaclass(ObjectTypeMeta)):
if kwargs:
for prop in list(kwargs):
try:
if isinstance(getattr(self.__class__, prop), property):
if isinstance(getattr(self.__class__, prop), property) or prop.startswith('_'):
setattr(self, prop, kwargs.pop(prop))
except AttributeError:
pass

View File

@ -64,6 +64,20 @@ def test_generate_objecttype_with_fields():
assert 'field' in MyObjectType._meta.fields
def test_generate_objecttype_with_private_attributes():
class MyObjectType(ObjectType):
_private_state = None
assert '_private_state' not in MyObjectType._meta.fields
assert hasattr(MyObjectType, '_private_state')
m = MyObjectType(_private_state='custom')
assert m._private_state == 'custom'
with pytest.raises(TypeError):
MyObjectType(_other_private_state='Wrong')
def test_ordered_fields_in_objecttype():
class MyObjectType(ObjectType):
b = Field(MyType)