Created
December 9, 2010 12:47
-
-
Save stasm/734676 to your computer and use it in GitHub Desktop.
Silme's new entity object
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
""" | |
silme.core.Entity represents single key:value pair | |
""" | |
__all__ = ['is_string','is_entity','Entity'] | |
def is_string(v): | |
return isinstance(v, basestring) | |
def is_entity(o): | |
return isinstance(o, Entity) | |
class Value(object): | |
def __new__(cls, *args, **kwargs): | |
i = args[0] | |
if i is None: | |
return | |
t = type(i) | |
if isinstance(i, Value): | |
return i | |
elif is_string(i): | |
cl = SimpleValue | |
elif t is list: | |
cl = ListValue | |
elif t is dict: | |
cl = DictValue | |
else: | |
cl = ComplexValue | |
return cl.__new__(cl, i) | |
class SimpleValue(str, Value): | |
def get(self, *args, **kwargs): | |
return self | |
class ComplexValue(Value): | |
def __new__(cls, *args, **kwargs): | |
return object.__new__(cls) | |
def __init__(self, value): | |
self._value = value | |
def __setitem__(self, key, value): | |
raise NotImplementedError() | |
def __getitem__(self, key): | |
raise NotImplementedError() | |
def __delitem__(self, key): | |
raise NotImplementedError() | |
def get(self, *args, **kwargs): | |
raise NotImplementedError() | |
class ListValue(list, ComplexValue): | |
def get(self, i=0, *args, **kwargs): | |
return self[i] | |
class DictValue(dict, ComplexValue): | |
def get(self, key=None, *args, **kwargs): | |
if key is not None: | |
return self[key] | |
return self.values()[0] | |
class Entity(object): | |
def __init__(self, id, value=None): | |
self.id = id | |
self._value = Value(value) | |
self.params = {} | |
def __repr__(self): | |
return '<entity: "%s">' % self.id | |
def get_value(self, *args, **kwargs): | |
"""Get the value of the entity. | |
You can pass a special `_getter` keyword argument which should be | |
a function to be used to get the value of the entity. This is helpful | |
if your Entities occasionally have non-standard values. You should | |
also consider sublassing ComplexValue and overriding its `get` method, | |
which might be preferable. | |
""" | |
_getter = kwargs.pop('_getter', None) | |
if _getter: | |
return _getter(self._value, *args, **kwargs) | |
try: | |
return self._value.get(*args, **kwargs) | |
except AttributeError: | |
return None | |
def set_value(self, value, *args, **kwargs): | |
self._value = Value(value) | |
value = property(get_value, set_value) | |
def __setitem__(self, key, value): | |
self._value[key] = value | |
def __getitem__(self, key): | |
return self._value[key] | |
def __delitem__(self, key): | |
del self._value[key] | |
@property | |
def values(self): | |
return self._value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment