Initialize field only once in Python
<p>I have file services.py with certain class MyCache in it. All instances of MyCache should share one "cache" field, so I made it static. In order to initialize cache there is static method that loads it. This method is called exactly once at the very start of the app.</p>

<p>The problem is that when I import services.py from other .py file and create instance of MyCache - it prints that cache is empty! </p>

<p>How can I fix it and make "cache" field shared by all instances of the class disregard of place from which they are created?</p>

<p>I can't get why this happens. Please help :)</p>

<p>services.py:</p>

<pre><code>class MyCache:
    cache = {}

    @staticmethod
    def initialize():
       MyCache.cache = load_from_file()
       print(len(MyCache.cache)) # prints 3

    def __init__(self):
       print(len(MyCache.cache)) # supposed to print 3, because initialize has been called earlier, but prints 0 when called from other_file.py
</code></pre>

<p>main.py:</p>

<pre><code>import services

if __name__ == '__main__':
    services.MyCache.initialize()
</code></pre>

<p>other_file.py:</p>

<pre><code>import services

services.MyCache().foo() # creates instance, prints 0 in MyCache.__init__
</code></pre>