Search code examples
pythonclassobjectpropertiesattributes

TypeError: object of type 'property' has no len()


I have this code of a class that contains a list _offers of custom Offer objects. For this list I created a property to allow access to it:

class OffersManager:    
    _offers: list[Offer] = []
    
    @property
    def offers(cls) -> list[Offer]:
        return cls._offers

The problem is that the program treats this list as a "property" object, so it gives me an error when I try to get the length of the list:

>>> len(OffersManager.offers)
>>> Traceback (most recent call last):
      File "<pyshell#1>", line 1, in <module>
        len(OffersManager.offers)
    TypeError: object of type 'property' has no len()

Can someone tell me the correct way to make a property return the attribute as a list?


Solution

  • Update from the comments: this is deprecated and may not work correctly, use the metaclass approach from SUTerliakov's answer instead.


    You need to mark the property as a class method, so it's bound to the class itself rather than the instances:

    class OffersManager:    
        _offers: list[OfferData] = []
        
        @classmethod
        @property
        def offers(cls) -> list[OfferData]:
            return cls._offers