I'm trying to create a class which maps to a mongoDB collection.
My code looks like this:
class Collection:
_collection = get_collection() # This seems not working
@classmethod
def get_collection(cls):
collection_name = cls.Meta.collection_name if cls.Meta.collection_name \
else cls.__name__.lower()
collection = get_collection_by_name(collection_name) # Pseudo code, please ignore
return collection
class Meta:
collection_name = 'my_collection'
I came across a situation where I need to assign the class variable _collection
with the return value of get_collection
.
I also tried _collection = Collection.get_collection()
which also seems not to be working
As a work-around, I subclassed Collection
and set value of _collection
in the child class.
Would like to know any simple solution for this.
Thanks in advance
As DeepSpace mentions, here:
the
get_collection
method is not yet defined when you call it. But moving this line after the method definition won't work either, since the method depends on theCollection
class (passed ascls
to the method), which itself won't be defined before the end of theclass Collection:
statement's body.The solution here is to wait until the class is defined to set this attribute. Since it looks like a base class meant to be subclassed, the better solution would be to use a metaclass:
Note however that if
Collection
actually inherit from a another class already having a custom metaclass (ie DjangoModel
class or equivalent) you will need to makeCollectionType
a subclass of this metaclass instead of a subclass oftype
.