mkohram mkohram - 1 year ago 93
Python Question

Computed static property in python

Is it possible to have a static property on a class that would be computed as a one off. The idea would be to be able to do it like so:

class Foo:
static_prop = Foo.one_off_static_method()

def one_off_static_method():
return 'bar'

I thought of using
as well.

Class Foo:
def __new__(cls):
cls.static_prop = ... do everything here

Not sure the implications of that though.

wim wim
Answer Source

If you want it computed at class definition time, see chepner's answer - although I would recommend just to use a module level function instead.

If you want it lazily evaluated, then you might be interested in a cached_property.

>>> from random import random
>>> from cached_property import cached_property
>>> class Foo(object):
...     @cached_property
...     def one_off_thing(self):
...         print('computing...')
...         return random()
>>> foo = Foo()
>>> foo.one_off_thing
>>> foo.one_off_thing

Note: it seems every man and his dog has an implementation of memo decorators in Python, this is one of many. If you're on Python 3, consider functools.lru_cache because it's in the core libraries.