Attempted relative import beyond top-level package Error - python-3.x

I have a folder xyz which contains two files ab.py and cd.py. Im trying to import cd.py in ab.py file.
Below is the folder structure:
/xyz
ab.py
cd.py
I have to import cd to ab
when i do
from . import cd
This gives me error as:
Attempted relative import beyond top-level package

If I understand correctly. xyz is a directory under your working directory.
In that case try to add the current directory to import path.
>>> import sys
>>> from pathlib import Path
>>> sys.path.append(Path.cwd())
And in ab.py use from xyz import cd
Additional references
Sibling package imports
Relative imports for the billionth time

Related

Cannot import functions in from one directory's subfolder to other pyhton files in same parent directories sub folders. How do I use init.py files

parent_folder /
subfolder1 /
subsubfolder1/
a.py
b.py
subsubfolder2/
c.py
d.py
e.py
subfolder2 /
subsubfolder2/
f.py
g.py
subfolder3 /
h.py
i.py
g.py
I want to import the functions from files h,i,g to all the subsubfolders py files. Can any one help me how do I do that.
I have tried using sys.path.insert(0 , 'path')
from h import funct1 , from g import funct1. It works
II get this error ImportError: attempted relative import with no known parent package when I do from .h import funct1 and I also want to Implement this in docker files. Is there any other way?
Thanks in advance !!
For your case it is best to use sys:-
for example to import in a.py use:
import sys
sys.path.insert(0,'../../subfolder3')
import h,i,g
Here we can use relative path in sys, '..' indicates moving one folder back
For Docker it is best to use relative path as:
import sys,os
sys.path.append(os.path.join(sys.path[0],'../../subfolder3'))
import h,i,g
This would work for docker. Please try and let me know if it works.

Relative import doesn't work : ImportError: attempted relative import with no known parent package

This are the files:
parent_directory:
parent_directory/ecommerce:
parent_directory/ecommerce/payments:
What I'm trying to do is to use a relative import in products.py in order to import database.py. I know that I can just write import database but I want to learn relative imports. I've also tried to import main.py from the top level directory, parent_directory, but that doesn't work either so I thought I'll just try to do the easiest relative import possible and that is, importing a file from the same package.
This is the code for products.py inside parent_directory/ecommerce:
from .database import Database
class Product:
pass
And this is the code from the database.py file inside parent_directory/ecommerce:
if __name__ == "__main__":
import products
x = products.Product()
class Database:
pass
print("file : {0:<35} || name : {1:<20} || package : {2:<20}".format(
str(__file__).split("\\")[-1],
str(__name__),
str(__package__),
))
I tried several things like:
executing products.py with -m like python -m products.py
creating a py venv
adding all and package inside the files.
Here is my init.py file from parent_directory/ecommerce:
__all__ = ["database", "products"]
__package__ = "ecommerce"
No matter what I do, I always get this error: ImportError: attempted relative import with no known parent package. I know that this question has been asked before. I've tried many things out but nothing worked. Do you have any idea how to fix this ?
I found the solution to my problem.
I have to be outside the package and use -m and instead of using / to send the path, I have to use . instead so :
python -m parent_directory.ecommerce.products
This will fix the problem but I have to execute this line outside the top-level package ( in my case, the top level package is parent_directory ).
# Inside products.py
from .database import Database # works
from ..main import SomeRandomClass # works
class Product:
pass
I've found a way to import files from parent directories, since it's very easy to import them from sub-packages by using absolute imports.
# inside parent_directory/ecommerce/products.py trying to import parent_directory/main.py
import sys
import os
current_file = os.path.realpath(__file__)
current_dir_ecommerce = os.path.dirname(current_file)
parent_dir_parent_directory = os.path.dirname(current_dir_ecommerce)
sys.path.insert(0, parent_dir_parent_directory)
import main # works
I just added the parent directory to sys.path.

How to import module present in parent directory to sub directory modules

I have my folder structure as below:
XYZ
- abc.py
- /123
- mn.py
XYZ is the parent directory, which is having file abc.py and sub-directory /123. Further this sub-directory contains mn.py file. Now i need to import abc in mn. How can I achieve this. Can someone please give some suggestion?
You could use the built-in sys module to add your package.
import sys
sys.path.insert(0, "/path/to/your/package_or_module")
# Rest of your code here.
In your case you could simply insert the path as below.
import sys
sys.path.insert(0, "..")
# Rest of your code here.
Import paths are always relative to the directory from which the Python interpreter runs. If you're running the Python interpreter from the XYZ directory, you can simply do:
import abc
in mn.py, since abc.py is located at the source root.

I can't import modules from other folders

I'm a bit new to the Python world. I'm using Python3 and having hard times with imports.
I was using PyCharm on Windows to write an application. Everything was working through the project until I switched to Linux and VS Code.
Now I can't use absolute imports for importing modules from other packages in the same project.
For example, I'd like to import from module cards all available card types.
I tested the classes and everything is ok. I'm only getting this issue with the import stuff.
The project structure:
/
|-cards
|-__init__.py
|-card.py
|-monster_card.py
|-spell_card.py
|-trap_card.py
|-ritual_card.py
|-deck
|-__init__py
|-deck.py
|-system
# This is the code in __init__.py in cads package
from . trap_card import TrapCard
from . spell_card import SpellCard
from . ritual_card import RitualCard
from . monster_card import MonsterCard
__all__ = [TrapCard, SpellCard, RitualCard, MonsterCard]
# The following line, for example, does not work from inside another package
# I'm trying to import the modules in cards from deck
from cards import TrapCard, MonsterCard, SpellCard, RitualCard
When I try to import packages from another folders I get this error message:
Traceback (most recent call last):
File "/root/git-repos/Yu-Gi-Oh/decks/deck.py", line 3, in
from cards import TrapCard, MonsterCard, SpellCard, RitualCard
ModuleNotFoundError: No module named 'cards'
When you call import *, python search the module from sys.path. You need to add your root dir into sys.path before call import stmt.
For your case, your root dir is /.
like:
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from cards import *
other way
Add file __init__.py into your root dir for make it become a module. Then change from cards import * to from .cards import *.

Python3 Importing module/package from sibling directories

Here is my code directory structure:
/root
-/proj1
--/module1.py
--/__init__.py
--/sub_proj1
---/module2.py
---/__init__.py
-/proj2
--/module3.py
If I want to import code from module2.py into module3.py I tried the following import statement:
from .proj1.sub_proj1 import *
but I am getting import error. Is thee anything I need to fix? I am not sure what I am doing wrong with relative imports.
Similar to this question:
Python import module from sibling folder
You need an __init__.py in your root and both project folders
Also this should be your import statement:
from ..proj1.sub_proj1 import *

Resources