Opened 4 months ago

Last modified 4 weeks ago

#29478 new Bug

cached_property decorator doesn't work with mangled method names

Reported by: Thomas Grainger Owned by: nobody
Component: Utilities Version: 2.0
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: yes
Easy pickings: no UI/UX: no

Description

import itertools

from django.utils.functional import cached_property

count = itertools.count()
count2 = itertools.count()
count3 = itertools.count()


class Foo:
    @cached_property
    def __foo(self):
        return next(count)

    @cached_property
    def foo2(self):
        return next(count2)

    @property
    def foo3(self):
        return next(count3)

    def run(self):
        print('foo', self.__foo)
        print('foo', self.__foo)
        print('foo', self.__foo)
        print('foo', self.__foo)
        print('foo2', self.foo2)
        print('foo2', self.foo2)
        print('foo2', self.foo2)
        print('foo2', self.foo2)
        print('foo2', self.foo2)
        print('foo3', self.foo3)
        print('foo3', self.foo3)
        print('foo3', self.foo3)
        print('foo3', self.foo3)
        print('foo3', self.foo3)


Foo().run()


"""
python cached_property_test.py 
foo 0
foo 1
foo 2
foo 3
foo2 0
foo2 0
foo2 0
foo2 0
foo2 0
foo3 0
foo3 1
foo3 2
foo3 3
foo3 4
"""

Odd it's not been reported before: https://code.djangoproject.com/search?q=cached_property+mangled

Change History (6)

comment:1 Changed 4 months ago by Tim Graham

Component: UncategorizedUtilities
Has patch: set
Patch needs improvement: set
Triage Stage: UnreviewedAccepted
Type: UncategorizedBug

comment:2 Changed 4 months ago by Harro

Had a look at this, and the Foo instance dict does contain the __foo (and the foo2, but not the foo3 as expected).

I think this is more a python thing where the double underscore is special and that is the reason it doesn't work and that it has nothing to do with the @cached_property decorator.

Last edited 4 months ago by Tim Graham (previous) (diff)

comment:3 Changed 3 months ago by Thomas Grainger

Patch needs improvement: unset

comment:4 Changed 3 months ago by Tim Graham <timograham@…>

In 09199734:

Refs #29478 -- Doc'd how to use cached_property with a mangled name.

comment:5 Changed 3 months ago by Tim Graham <timograham@…>

In 2a637a45:

[2.1.x] Refs #29478 -- Doc'd how to use cached_property with a mangled name.

Backport of 09199734d383691ecf6d163894b447ca45e0ef82 from master

comment:6 Changed 3 months ago by Tim Graham

Patch needs improvement: set
Note: See TracTickets for help on using tickets.
Back to Top