pydanny/cached-property

No compatible with `__slots__`

Open

#69 opened on Aug 30, 2017

View on GitHub
 (3 comments) (0 reactions) (0 assignees)Python (79 forks)github user discovery
bugenhancementhelp wanted

Repository metrics

Stars
 (705 stars)
PR merge metrics
 (No merged PRs in 30d)

Description

Hi. Very interresting project. I was about to develop the same thing, but made a research first and found this

The problem is that it doesn't support the use of __slots__

Demonstration:

>>> from cached_property import cached_property
>>> class C:
...     __slots__ = 'x',
...     @cached_property
...     def y(self):
...         return 'y'
... 
>>> c = C()
>>> c.y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/site-packages/cached_property.py", line 26, in __get__
    value = obj.__dict__[self.func.__name__] = self.func(obj)
AttributeError: 'C' object has no attribute '__dict__'

I have a little wrapper for this named slot_wrapper somewhere.

Here is a simplified version:

def slot_wrapper(attrname, slot, cls):

    class InnerDescriptor:

        def __get__(self, obj, cls):
            return slot.__get__(obj, cls)

        def __set__(self, obj, val):
            slot.__set__(obj, val)

return InnerDescriptor(attrname)

It takes the descriptor under the slot and replace it (__slots__ underly special descriptors, but they remains descriptors after all). It needs adjustments with your code in order to work... I use it with metclass so it got instaciate after the creation of a class wich have __slots__.

My demand is between a bug report, a feature request and an enhacement proposal!

Contributor guide