Cannot clearly understand right way to create CRUD interface for entity.
For example:
I've got entity Event with variables date, place and name.
I've got basic constructor for this entity with default (nullablle) values.
class Event:
def __init__(self, date=None, name=None, place=None):
self.date = date
self.name = name
self.place = place
Trying to figure out pythonic way to create update handler for this entity, which allows me to update custom number of entity fields (for example: update name and place, without specifying date).
How I see this:
Use list of custom attributes in update method like update_event(**kwargs), then parse **kwargs list and match them with entity using .hasattr() or .getattr() functions.
Its seems working (and able to find actual diff between entities, which is useful too), but looking pretty harsh.
Basic version with setting all values from kwargs looks like this:
def update_event(self, **kwargs):
for key, value in kwargs.items():
self.__setattr__(key, value)
return self
If we need to check if for diff, we already got:
def update_event(self, **kwargs):
for key, value in kwargs.items():
if self.__getattribute__(key) != value:
# We got diff
self.__setattr__(key, value)
else:
# We got same value stored already
return self
Maybe im missing something and there are more elegant and simple solutions to this problem, or some design patterns to look for?
Tnx for answers and sorry for dummy questions.
UPD: One more point I see: simple __setattr__ doesn't check that such variable exists. So, if **kwargs contains invalid argument name I get Attribute Error.
The obvious fix for that is to create check for .hasattr() but as I see it will return False if variable declared but has None value.
update_event()method, using.hasattr()etc.update_event()code to the topic.Event.