Computed static property in python

Is it possible to have a static class property that will be evaluated as one. The idea would be to do it like this:

class Foo:
    static_prop = Foo.one_off_static_method()

    @staticmethod
    def one_off_static_method():
        return 'bar'

I was thinking about using __new__.

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

Not sure if this could happen.

+4
source share
3 answers

If you want it to be computed during class definition, see the chepner answer - although I would recommend using the module level function instead.

If you want it to be lazily evaluated, you might be interested 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
computing...
0.5804382038855782
>>> foo.one_off_thing
0.5804382038855782

. , Python, . Python 3, functools.lru_cache, .

+3

, one_off_static_method . , , , class. , .

class Foo:
    def _one_off_static_method():
        return 'bar'

    static_prop = _one_off_static_method()
    del _one_off_static_method
+1

, : -)

.

class CachedStaticProperty:
    """Works like @property and @staticmethod combined"""

    def __init__(self, func):
        self.func = func

    def __get__(self, inst, owner):
        result = self.func()
        setattr(owner, self.func.__name__, result)
        return result

:

  • .
  • , .

. .

+1

Source: https://habr.com/ru/post/1654614/


All Articles