Search code examples
pythonstatic-methods

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()

    @staticmethod
    def one_off_static_method():
        return 'bar'

I thought of using __new__ as well.

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

Not sure the implications of that though.


Solution

  • 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, per instance, then you might be interested in functools.cached_property.

    >>> from random import random
    >>> from functools 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
    

    Note: stdlib functools.cached_property requires Python 3.8+, for Python < 3.8 you can pip install cached_property.