Python import error when making a test package - python-3.x

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.

Related

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

Import error in python, when modules have imports [duplicate]

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

Erro when I to try to use import

I am coding an application that has 2 services integrated with rabbitmq(publisher and consumer).
I have a folder lib that contains a class manager_mq, that is used to manage the process of pub/sub of my application.
My structured the directory to be like the image:
In my consumer or publisher .py file, When I try to import manager_mq an error is returned.
My import to be like that:
from services.lib.manager_mq import Manager
However, an error is returned on the console.
Traceback (most recent call last):
File "consumer.py", line 5, in <module>
from services.lib.manager_mq import Manager
ModuleNotFoundError: No module named 'services'
I am tried to use relative import but the error occurs yet.
Traceback (most recent call last):
File "consumer.py", line 5, in <module>
from ..lib.manager_mq import Manager
ImportError: attempted relative import with no known parent package
How can I solve this problem?
Here both absolute and relative imports won't work. For more information, check out Importing from Parent Directory.
In this case it would probably be the easiest to use sys.path to add the lib to the path.
application
├── consumer
│ └── __init__.py
│ └── consumer.py
└── lib
└── __init__.py
└── manager_mq.py
manager_mq.py test code:
class Manager:
def __init__(self) -> None:
print('test')
consumer.py test code:
import sys
sys.path.append("../lib")
from manager_mq import Manager
m = Manager()

Is it possible to fix problems with relative imports?

I have some problems with import mechanic. For example I have a tree like this:
├── my_package
| ├── first.py
| └── second.py
└── test.py
second.py:
def second_func():
print('Hello World')
first.py:
from second import second_func
def first_func():
second_func()
test.py:
from my_package.first import first_func
first_func()
And when I try to run test.py I get this error:
ModuleNotFoundError: No module named 'second'
It feels like second.py is not searched in my_package, but in the directory where my_pacakage and test.py are located. This is a strange mechanics, because if I have a ready-made package, I don’t want to create some new file in it, I want to interact with it from another place.
First create a __init__.py in the my_package. Change import statement of the first.py to the following
from .second import second_func
Then run python test.py. It should give Hello World

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