Clippit
Clippit

Reputation: 906

How to import variables defined in __init__.py?

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__.

Upvotes: 8

Views: 4523

Answers (2)

Winston Ewert
Winston Ewert

Reputation: 45039

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.

Upvotes: 4

Fred Foo
Fred Foo

Reputation: 363627

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__

Upvotes: 7

Related Questions