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__
.
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__
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With