Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import variables defined in __init__.py?

Tags:

python

I'm a little confused about how importing works. Assume:

package/
    __init__.py
    file1.py

In __init__.py:

from file1 import AClass
__version__ = '1.0'

In file1.py:

Class AClass(object):
    def bar():
        # I want to use __version__here, but don't want to pass
        # it through the constructor. Is there any way?
        pass

If I use from . import __version__ in file1.py it just says ImportError: cannot import name __version__.

like image 921
Clippit Avatar asked Sep 05 '12 15:09

Clippit


2 Answers

You've got a circular dependency because both files try to import each other. Move __version__ to a separate module, say package/version.py, then import that in both others with

from .version import __version__
like image 131
Fred Foo Avatar answered Sep 28 '22 11:09

Fred Foo


Try:

__version__ = '1.0'
from file1 import AClass

You need to assign the constants before you import the module so that it'll be in place when you try to import it.

EDIT: larsmans suggestion to avoid the circular dependency is a good idea.

like image 31
Winston Ewert Avatar answered Sep 28 '22 10:09

Winston Ewert