I’m working on a class that needs to be given it’s __dict__ attribute via __init__ injection like this:
class Torrent(Model):
def __init__(self, d):
super(Torrent, self).__init__('torrents')
self.__dict__ = d
And need to make sure not to change the structure of the object because the instance is going to end up in a NOSQL db. I thought that __slots__ could be helpful, but I need to define it dynamically.
Is there a way to make it possible without a metaclass ?
Use a factory function:
Note that in order to use slots:
slots_iterablemust be an iterable of strings__dict__(ie. that is not__slots__only)Now, you say you ‘need to make sure not to change the structure of the object’, using
__slots__is not the only (and probably not the best either) solution to your issue: using slots makes your class harder to use in code.Instead, you could do the following:
This way, you’re sure that only your actual fields will be saved to your db.