Ahmad Farid
Ahmad Farid

Reputation: 14774

What's an alternative to using cached_property for a collection in python?

@cached_property
def my_collection():
    return [1, 2, 3]

def do_stuff():
    for i in my_collection:
        print i

I try to cache a list, set or map that I can iterate on. However, doing that, I get TypeError: 'cached_property' object is not iterable. Any other workarounds?

Upvotes: 0

Views: 2023

Answers (1)

Ivan Blinov
Ivan Blinov

Reputation: 141

The reason is you are trying to apply this decorator to a function, but it makes no sense, because it's designed for instance methods. This will work:

class Foo:
    @cached_property
    def my_collection(self):
        return [1, 2, 3]


def do_stuff():
    for i in Foo().my_collection:
        print i

Upvotes: 1

Related Questions