How can I access `__version__` defined in `__init__.py` from another module?

Say I have a package with this layout:

mypackage/
    __init__.py
    module_a.py
# __init__.py
from .module_a import function_a

__all__ = ["function_a"]
__version__ = "0.0.1"

In function_a from module_a.py, I would like to print the contents of __version__ to a debug message. Obviously, attempting to import __version__ from mypackage results in a circular import.

How can I accomplish this?

Do the import in function_a not at the module level I think will work.

2 Likes

Indeed it does, thanks!

The other way would have been to put the version into its own mypackage/version.py then you could import in __init__ as well as any other of mypackage’s modules at the module level.

2 Likes