ImportError: cannot import name some_name from '__main__' - python

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:
When attempting to import it from some other location e.g. .. pycharm does complain:
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?

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

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

Related

Python ImportError. How can I import modules among packages?

I was working on a project with this type of folder tree:
-main.py
-Message_handlers
-__init__.py
-On_message.py
-Other_modules.py
-Exceptions_handler
-__init__.py
-Run_as_mainException.py
Message_handlers and Exceptions_handler are two packages, now my problem is that from inside the module On_message.py I can't import the class Run_as_mainException (inside of the module Run_as_mainException.py) using this code
# This is On_message.py
from ..Exceptions_handler.Run_as_mainException import Run_as_main_Exception
This line gives the error: ImportError: attempted relative import with no known parent package
p.s. Every file has a class inside with the same name of the file, example:
# This is Run_as_mainExample.py
class Run_as_mainExample:
def __init__(self):
# rest of the code
Can anyone help me please?
You have to assume that you're running everything from the level where main.py is located. This means, imagine that you execute python main.py, and you want to import Run_as_main_Exception from main.py, what should you do?
from Exceptions_handler.Run_as_mainException import Run_as_main_Exception
Try using that line in your On_message.py file, and you shouldn't have any problem when running your script from that exact location (remember, the same level where main.py is located)

`Importlib` not actually importing modules?

I'm trying run an env_setup script that imports modules used in my main_script. But despite successfully running env_setup.py the modules are not being imported (presumably it is being run in its own environment).
Previously I know I have somehow sucesfully used:
from env_setup import *
However this fails for me now.
I tried a second approach using:
importlib.util.spec_from_file_location(name, location)
But this also fails.
Below is an example of what I am attempting (using the second approach in my main_script.py):
Example env_setup.py script:
import datetime # import module
print("modules imported!!!") # confirm import
Example main_script.py script:
# This first section should import `datetime` using `env_setup.py`
import importlib
spec = importlib.util.spec_from_file_location(
name='setup',
location='/home/solebay/my project/env_setup.py' # path to `set_up` script
)
my_mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(my_mod)
# This returns "modules imported!!!"
# Here we run a basic command to check if `datetime` was imported...
now = datetime.datetime.now()
print(now.strftime('%H:%M:%S on %A, %B the %dth, %Y')) # Should print time/date
# NameError: name 'datetime' is not defined
How do I get python to actually import the required modules into the environment running main_script.py? It creates a __pycache__ folder so I know the path is correct.
After dynamically importing a module you can either access the module directly by using my_mod.function() or import everything (imitate from module import *) like so:
import sys
sys.modules["setup"] = my_mod
from setup import *
del sys.modules["setup"] # Optional
After lots of searching I decided:
from env_setup import *
Should absolutely work.
I moved my most recent scripts to a fresh directory with a simpler tree and everything works.
I'm thinking it was a bug?
Update (Not a bug):
As per the useful suggestion of Bharel I ran..
import os
os.getcwd() # Returned 'wrong' directory
os.listdir() # Returned 'wrong' listing
Visual inspection of the folder tree showed that env_setup.py was present, but this file and others were absent from the true listing returned by os.listdir().
I'm running my code through the IDE "Atom" using the "Hydrogen" module. I opened a new window, added a new project folder and ran the command again and it updated.
I'm assuming I moved a folder and Atom didn't have a chance to update the path.
End result:
from env_setup import *
Works prefectly.

How do I import a remote module, that imports a local module?

I have my program importing a module from a different location using importlib. This imported module (let's call it A) imports some other custom module located next to it (let's call it B).
My_Project\
│
└─── my_program.py
Some_Other_Location\
│
├─── A_module_my_program_wants_to_import.py
└─── B_module_A_imports.py
When I import A without it importing B, it works just fine:
# Sample from my_program.py
path = Some_Other_Location\A_module_my_program_wants_to_import.py
spec = importlib.util.spec_from_file_location("A", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
However, when in A I import B:
# Sample from A_module_my_program_wants_to_import.py
import B_module_A_imports
Or
from B_module_A_imports import foo
And I run my program, I get:
Build error: No module named 'B_module_A_imports'
And a traceback to where I import in my program, and A
I've tried specifying submodule_search_locations=Some_Other_Location of spec_from_file_location but it didn't help.
So the question is how do I import a remote module, that imports a local module?
I've found a workaround, not a proper solution though. The workaround is as follows:
I've realised that it's trying to load B where my_program is located and obviously didn't find anything. However, it is possible to trick the loader to find the file, by adding Some_Other_Location to sys.path. So this is what the import part of my_program looks like:
directory = Some_Other_Location
sys.path.append(directory)
path = Some_Other_Location\A_module_my_program_wants_to_import.py
spec = importlib.util.spec_from_file_location("A", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
sys.path.remove(directory)
This works just fine, however, I'm still open for actual solutions!

gRPC generated python script fails to find a local module in the same directory? [duplicate]

In python 2 I can create a module like this:
parent
->module
->__init__.py (init calls 'from file import ClassName')
file.py
->class ClassName(obj)
And this works. In python 3 I can do the same thing from the command interpreter and it works (edit: This worked because I was in the same directory running the interpreter). However if I create __ init __.py and do the same thing like this:
"""__init__.py"""
from file import ClassName
"""file.py"""
class ClassName(object): ...etc etc
I get ImportError: cannot import name 'ClassName', it doesn't see 'file' at all. It will do this as soon as I import the module even though I can import everything by referencing it directly (which I don't want to do as it's completely inconsistent with the rest of our codebase). What gives?
In python 3 all imports are absolute unless a relative path is given to perform the import from. You will either need to use an absolute or relative import.
Absolute import:
from parent.file import ClassName
Relative import:
from . file import ClassName
# look for the module file in same directory as the current module
Try import it this way:
from .file import ClassName
See here more info on "Guido's decision" on imports in python 3 and complete example on how to import in python 3.

Importing __init__

I am trying out the answer in this.
The __init__.py file in a folder named MyLibs contains:
LogFile = r'D:\temp'
In utils.py in the same folder MyLibs, I tried various ways to access the LogFile variable:
from __init__ import *
print LogFile #Gives: NameError: name 'LogFile' is not defined`:
and:
import __init__
print MyLibs.LogFile #Gives: NameError: name 'MyLibs' is not defined
I got the errors while executing from MyLibs.utils import *
What is the fix I must do? I prefer a method where I can reference LogFile directly without having to add namespace prefixes.
My mistake.
The updated __init__.py was somehow not executed. I started a new Python session and it worked.
Sorry for the false alarm.
Not sure how to do this with 2.7's implicit relative imports, but you could try this:
from __future__ import absolute_import
from . import LogFile
If you're running the Python module directly, you need to run it with python -m MyLibs.utils rather than python MyLibs/utils.py.

Categories