WestCoastProjects
WestCoastProjects

Reputation: 63182

ImportError: cannot import name some_name from '__main__'

A variable isDevelopment is inside the manager/__init__.py file:

 isDevelopment = True

Within the same directory a file fusion.py attempts to import it at the file level:

from . import isDevelopment

Note: pycharm is ambivalent to it: the import is not flagged in any case:

enter image description here

When attempting to import it from some other location e.g. .. pycharm does complain:

enter image description here

When running

 python3 manager/fusion.py

the following occurs:

 ImportError: cannot import name 'isDevelopment' from '__main__'

Another attempt per one of the suggestions:

from ..manager import isDevelopment

This results in:

ValueError: attempted relative import beyond top-level package

Why is this attempted import not working - and what needs to be changed?

Upvotes: 0

Views: 893

Answers (2)

Kristian
Kristian

Reputation: 502

./test.py
./manager/__init__.py
./manager/fusion.py

__init__.py

isDevelopment = True

./manager/fustion.py

from . import isDevelopment

def checkDevelopment():
    print("isDevelopment = {0}".format(isDevelopment))

./test.py

import manager

if __name__ == "__main__":
    print("isDevelopment = {0}".format(manager.isDevelopment))
    manager.checkDevelopment()

Execute

python3 ./test.py

Output

isDevelopment = True
isDevelopment = True

Question

Are you attempting to execute manager/fusion.py to set the module or do you want it to be part of your executable application? If you simply want to know the value of isDevelopment within the manager module, that can be achieved. If you want an executable function contained in manager explore entry points using setup.py

Upvotes: 1

Javier
Javier

Reputation: 1087

__init__.py is used to initialize the package. According to documentation at https://docs.python.org/3/tutorial/modules.html#packages

Users of the package can import individual modules from the package

You don't import what is in __init__.py, it's run automatically when you do an import.

In the simplest case, init.py can just be an empty file, but it can also execute initialization code for the package

As isDevelopment is not a module you cannot import it! If you have another module fusion2.py you could import it with

from . import fusion2

and there you should be able to see isDevelopment.

Upvotes: 0

Related Questions