Computed static property in python
<p>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:</p>

<pre><code>class Foo:
    static_prop = Foo.one_off_static_method()

    @staticmethod
    def one_off_static_method():
        return 'bar'
</code></pre>

<p>I thought of using <code>__new__</code> as well.</p>

<pre><code>Class Foo:
    def __new__(cls):
         cls.static_prop = ... do everything here
</code></pre>

<p>Not sure the implications of that though.</p>

<p>If you want it computed at class definition time, see <a href="http://stackoverflow.com/a/39498950/674039">chepner's answer</a> - although I would recommend just to use a module level function instead.</p>

<p>If you want it lazily evaluated, then you might be interested in a <a href="https://pypi.python.org/pypi/cached-property/" rel="nofollow"><code>cached_property</code></a>.  </p>

<pre><code>&gt;&gt;&gt; from random import random
&gt;&gt;&gt; from cached_property import cached_property
&gt;&gt;&gt; class Foo(object):
...     @cached_property
...     def one_off_thing(self):
...         print('computing...')
...         return random()
...     
&gt;&gt;&gt; foo = Foo()
&gt;&gt;&gt; foo.one_off_thing
computing...
0.5804382038855782
&gt;&gt;&gt; foo.one_off_thing
0.5804382038855782
</code></pre>

<p><em>Note:</em> 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 <a href="https://docs.python.org/3/library/functools.html#functools.lru_cache" rel="nofollow">functools.lru_cache</a> because it's in the core libraries.  </p>

python static-methods