Python NDB: what's the best way to have a set instead of a list in a property?
in NDB you have duplicate properties, they behave like a native python list, but I want them to behave the same as native sets. I need to have a set of keys without duplicates. in python you can remove duplicates like the_list = list(set(the_list))
,
but how would you implement this so that it is automatic and I don't think about it?
source to share
Three ways come to mind:
- list enforcement (duplicate property) is unique with the setter method, which inserts only unique values;
- Likewise, a forced list is unique with the _ pre_put_hook () method ;
- use the key on each object as your list, ndb will make sure they are unique.
source to share
Another option would be to subclass ndb.Property. Some examples here: https://cloud.google.com/appengine/docs/python/ndb/subclassprop
source to share
I believe the correct strategy would be to create a custom SetProperty that subclasses the ListProperty to enforce your requirements.
Read about subclass properties. https://cloud.google.com/appengine/docs/python/ndb/subclassprop
I believe this is the correct way to implement this type of property, not _pre_put. It is usually too late for appropriate review and feedback.
You can write custom setters, however you cannot be a netname, so it will look odd.
Another alternative might be to use a validator that is allowed to enforce a value. See https://cloud.google.com/appengine/docs/python/ndb/properties#options
source to share