Import error in python, when modules have imports [duplicate] - python-3.x

Question
When I try to activate main.py on linux bash with the command as follows,
python3 main.py
The error message looking as below keeps appearing, and I cannot figure out why!!
File "main.py", line 1, in <module>
import folder_beta.util_one
File "folder_beta/util_one.py", line 1, in <module>
ModuleNotFoundError: No module named 'util_two'
Questions in more detail
The folder tree looks like as below:
folder_alpha
├── main.py
└── folder_beta
├── __init__.py (empty)
├── util_one.py
└── util_two.py
main.py
import folder_beta.util_one
import folder_beta.util_two
....
util_one.py
import util_two
...
When I executed the 'util_one.py' alone, it works perfectly fine but when I executed the main.py, the error keeps appearing.
Can anyone tell me how to fix this problem, please?

That is an implicit relative import, it would have worked in Python 2 but it's no longer allowed in Python 3. From PEP 8:
Implicit relative imports should never be used and have been removed in Python 3.
In util_one.py module, change it to:
from folder_beta import util_two

Related

Python import error when making a test package

I keep having this error when I launch my code:
File "h:\a_path\source\tests\testClient.py", line 1, in <module>
from .. import client
ImportError: attempted relative import with no known parent package
Here is my program structure:
├source
├── tests
│      ├── __init__.py
│      └── testClient.py
├── __init__.py
├── client.py
I just want to make a test module for the module client.py
Here's the code I have in testClient.py :
from .. import client
def testClient():
client = client.Client()
I have looked up a lot of tutorial online but nothing worked so any help would by highly appreciated.
I tied to change the first line to "import ..client" but it was considered invalid synthax.

How to import classes and function from files within the same dir as main.py in Python 3.9?

I am struggling with importing local source files that reside in the same directory as main.py in Python 3.9. I had it working before but
couldn't tell why it was working. After a while it stopped working.
I created a minimal example to reproduce the problem with the structure shown below.
I have read some available answers that suggest using from . import car in main.py which resulted in the
following Error:
(venv) [.../pyimport_example/productname] python3 ./main.py
Traceback (most recent call last):
File "/Users/myUser/pyimport_example/productname/./main.py", line 1, in <module>
from . import car
ImportError: attempted relative import with no known parent package
Got the same error when using from .car import Car
I have also tried to run main.py as a module as suggested in "Relative imports in Python 3:
(venv) [.../pyimport_example/productname] python3 -m main.py
Traceback (most recent call last):
File "/usr/local/Cellar/python#3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 188, in _run_module_as_main
mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
File "/usr/local/Cellar/python#3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py", line 111, in _get_module_details
__import__(pkg_name)
File "/Users/myUser/pyimport_example/productname/main.py", line 2, in <module>
from .car import Car
ImportError: attempted relative import with no known parent package
The answer to "Relative imports in Python 3 seems to focus on the case where one want to run a python file as a
script inside a package, which is not the problem I am having.
My sample project
pyimport_example
├── README.md
├── productname
│   ├── __init__.py
│   ├── car.py
│   └── main.py
└── venv
├── bin
├── include
├── lib
└── pyvenv.cfg
content of main.py
from .car import Car
def main():
print("Maria ist cool.")
mycar = Car("Ford", "Mustang", "1966")
mycar.print_car()
if __name__ == '__main__':
main()
contents of car.py
class Car:
def __init__(self, make, model, year_manufacture):
self.make = make
self.model = model
self.year_manufacture = year_manufacture
def print_model(self):
print("{0} {1} {2}".format(self.year_manufacture, self.make, self.model))
Is there a fix without modifying the system path?
You have to modify your __init__.py-File.
In the folder productname you wanna specify what imports you can run from a module on the same level:
from .car import *
Now you should be able to import your file into your main.py with:
from car import Car

Error when importing variable from different script from different directory

I was working on a project where I was training a neural network and displaying information using a GUI in Python. However, I have a constant problem with importing modules. This is the error I get when trying to run Visualizer.Main
Traceback (most recent call last):
File "/home/user/SplineTrajectoryGenerator/Visualizer/Main.py", line 3, in <module>
from Visualizer.Field import Field
File "/home/user/SplineTrajectoryGenerator/Visualizer/Field.py", line 3, in <module>
from Visualizer.Utils import loadImage
File "/home/user/SplineTrajectoryGenerator/Visualizer/Utils.py", line 3, in <module>
from NeuralNetworks.Pose import Pose2D
File "/home/user/SplineTrajectoryGenerator/NeuralNetworks/Pose.py", line 4, in <module>
from Visualizer.Utils import constraint
ImportError: cannot import name 'constraint'
However, the strange thing is that the variable exists and can be found in Utils.py in the Visualizer folder. I was told that using the _init__.py
allows a directory to be used as a module to import methods and classes from scripts in other directories. I'm still confused about why this error happens when the variable exists. For reference the tree of all the files look like this.
.
├── NeuralNetworks
│ ├── __init__.py
│ ├──Main.py
│ └──Pose.py
├──README.md
└── Visualizer
├── Assets
│ ├── Field.png
│ └── Robot.png
├──Field.py
├── __init__.py
├──Main.py
├──Robot.py
└──Utils.py
In case you need to see the scripts, I have attached the whole folder below with this link. Any help would be greatly appreciated.
You seem to have a cyclic dependency between Visualizer.Utils and NeuralNetworks.Pose`:
from Visualizer.Utils import loadImage
File "/home/user/SplineTrajectoryGenerator/Visualizer/Utils.py", line
3, in
from NeuralNetworks.Pose import Pose2D
File "/home/user/SplineTrajectoryGenerator/NeuralNetworks/Pose.py",
line 4, in
from Visualizer.Utils import constraint
Python does not support cyclic dependencies - and that's actually a GoodThing(tm) since those are design issues (two modules should not depend on each other). The canonical solution is to create a new module for objects (classes, functions, whatever) that are necessary to both modules (ie in your case create a distinct module for 'constraint').

ModuleNotFoundError: cannot import local file

I have a module with multiple files structured like this:
/bettermod/
├── __init__.py
├── api.py
├── bettermod.py
├── errors.py
└── loggers.py
From bettermod.py, I'm trying to import two things:
a class called API from api.py
the whole errors.py file
For the first thing, it is quite easy, I just have to do this:
from .api import API
However, for importing the whole errors.py file, I'm encountering a problem; I'm trying to do like this:
from . import errors
which should work, according to this python documentation, but it's raising the following error:
File "/path/to/bettermod/bettermod.py", line 10, in <module>
from . import errors
ModuleNotFoundError: No module named 'bettermod'
Edit: when debugging, I found that __name__ was equal to bettermod.bettermod
From docs:
Note that relative imports are based on the name of the current module.
I cannot tell you what is wrong with certainty, but there is a smell: bettermod package has a bettermod module. You want to do from bettermod.bettermod import MyBetterClass? I doubt it. In Python files ARE namespaces, so choosing your file and directory names is also an API design. Just keep that in mind.
I suspect the problem is masked by the name collision. Try this. If you run python in bettermod directory and say import bettermod you are importing bettermod\bettermod.py. And . is relative to the bettermod.py module. Now try to run python in directory above bettermod package directory. It will work because now . resolves to bettermod package.
Try:
import mymodule
mymodule.__file__
This will tell what mymodule is. For packages, it will show path to __init__.py. This will help you to orient yourself. Also look up PYHTONPATH and how you can use it to make sure you are importing from the right path.

why does import module in same directory gets error

directory structure
test/
__init__.py
line.py
test.py
test.py
from . import line
output:
Traceback (most recent call last):
File "test.py", line 1, in <module>
from . import line
ImportError: cannot import name 'line'
I know I can just import line. but it may import standard library in python3.
why did this error happen? does python3 support this syntax?
ps: I'm not in interactive console and test directory has already been a package
I'm not sure if you can import module with the same name as library utilities directly. However, you could consider putting your modules inside a package, so your directory structure would look like:
.
├── main.py
├── package
│   ├── __init__.py
│   ├── line.py
│   ├── test.py
Where __init__.py might have some setup commands (you can omit this file if you have none) and in main.py you can do the following:
from package import line
...
Within the directory package if you'd like to say, import line.py in test.py you can use the syntax:
from . import line
Note relative imports (using the from . notation) will only work inside the script and not in the interactive console. Running the test.py ( if it's using relative imports) directly will also not work, although importing it from main.py will work.

Resources