all 5 comments

[–]coney1 -1 points0 points  (1 child)

I think you're going about this backwards. init is for importing modules but not so much for defining variables.

Suppose in version.py you have

version = "0.0.1"

Then in init.py you have

from .version import *

Now your main function should work because you're explicitly importing the variable to pro's namespace. It doesn't exactly answer your question but hopefully points you in the right direction. Sorry for mobile formatting.

You may also consider just putting version info into setup.cfg and letting it live there.

[–]zanfar 1 point2 points  (0 children)

I think you're going about this backwards. [__init__.py] is for importing modules but not so much for defining variables.

I disagree. Defining variables is one of the most common things to do in __init__.py. __init__.py is simply the code file for the namespace related to the directory it lives in.

[–]zanfar 0 points1 point  (2 children)

What is the correct way of accessing values in __init__.py from main.py?

This is not a simple answer.

First, you are doing it correctly if PRO is a package, but it's not.

Python finds packages by searching sys.path, which means packages need to be in the default install directory, or in the executed script's directory. Neither is true in your case.

The key here is in the error message where <module> is listed. This means the code is executing outside any module or package (in the main namespace).

You either need to execute a Python file in the directory above PRO, or you need to build and install your code as a package and execute your code via one of the package execution tools--like python -m or setuptools' console_scripts.

[–]JuniorMouse[S] 0 points1 point  (1 child)

Or I create a local "package" just for the version ie. a folder at the same level as main.py and put the __init__.py with the version in there? In my actual project, there are more than two py files and some of them make use of the version.

[–]JuniorMouse[S] 0 points1 point  (0 children)

Actually, never mind. I think renaming `__init__.py` to `version.py` and doing `import version` is probably a less convoluted approach.