Search code examples
pythoninheritanceglobal-variablesmodularity

Is it possible for `topmost.__init__.py` to access global variables in `topmost.submodule.__init__.py`?


If my Python library topmost is structured as such:

topmost
    /__init__.py
    /submodule
      /__init__.py

Is it possible for topmost.__init__.py to access global variables in topmost.submodule.__init__.py?

With the topmost.submodule.__init__.py, there should be some global variables:

def characterize(input):
    global abc 
    abc = load_abc_model()
    return abc.func(input)

I've tried this in topmost.__init__.py but the global variables in topmost.submodule.__init__.py is still not accessible:

from __future__ import absolute_import

from topmost import submodule

__import__('submodule', globals())

But only the abc global variable isn't accessible on the topmost.


Solution

  • A global variable declared/defined through/within a function will appear (in the global scope) when the function is first executed.

    Proof:

    $ python3
    Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 'abc' in globals()
    False
    >>> def foo():
    ...     global abc
    ...     abc = 123
    ...     print('foo')
    ... 
    >>> 'abc' in globals()
    False
    >>> foo()
    foo
    >>> 'abc' in globals()
    True
    >>> 
    

    With the current setup:

    topmost
        /__init__.py
        /submodule
          /__init__.py
    

    and:

    def characterize(input):
        global abc 
        abc = load_abc_model()
        return abc.func(input)
    

    topmost.submodule.abc will go live only after topmost.submodule.characterize() is called.