Import from a parent's parent package (Python) - python

The following is my folder structure:
/experiments
/experiment_1
/experiment_2
/experiment_3
/src
/sample.py
helper.py
All experiments share some code, which I have exported into helper.py. Now I'm trying to import a function from helper.py into sample.py:
from ...helper import my_function
and I get the following error:
ImportError: attempted relative import with no known parent package
Please note that I have tried many solutions offered here, but none worked.

create a __init__.py file in your parent folder.

The above question is related to
Importing files from different folder
The solution is to add the following lines in the sample.py:
import sys
sys.path.insert(1, 'path-to-experiments')
from helper import get_json

Related

Import script from another script in python

I have imported a repo using git and when I try to run a file, it shows that "it could not be resolved".
The running script has:
import craft_utils
import test
import imgproc
import file_utils
The imported things are all script.
I have attached the screenshots for the error and hierarchy.
How can I solve this? Thanks.
try adding an empty file named __init__.py in the root folder CRAFT-pytorch (instead of the basenet folder)
create a empty file named __init__.py
it would solve the issue
Add a file inside of the folder called __init__.py
First you need to create an empty file named __init__.py in the folder CRAFT-pytorch
Second add these line at the top of the file you're trying to running, before the imports:
import os
import sys
import inspect
app_path = inspect.getfile(inspect.currentframe())
main_dir = os.path.realpath(os.path.dirname(app_path))
sys.path.insert(0, main_dir)
import craft_utils
import test
import file_utils

Relative import of python module from current working directory

In the current working directory , i have following structure
Project
__init__.py
-RestApi
__init__.py
app.py
query_generator
-testfolder
__init__.py
test1.py
I want to call query_generator from test1.py , I tried calling
from . RestApi.query_generator import *
but getting following error
ImportError: attempted relative import with no known parent package
This question might be duplicate of following Importing files from different folder , Python relative-import script two levels up, Attempted relative import with no known parent package . But I am not able to solve it for my current problem
Try using below import:
from Project.RestApi.query_generator import *
There are multiple ways to achieve this.
you can add path till Project dir in your PYTHONPATH variable
export PYTHONPATH=$PYTHONPATH:<path_leading_to_Project>/Project
Then inside test1.py you can import the query_generator module using:
from RestApi.query_generator import *
Advantage of doing in such a way is if you execute your script from any working directory, it will work

import .py script on same folder

I've a python file named sample.py which has some functions and another python file from which I want to access the functions of the sample.py. I've tried the code below which is working fine if I include the directory in the import statement.
from Integrated.sample import *
But the folder can't be the same for my application. Also, I referred another problem in stackoverflow similar to my issue, tried one of the answers
from .sample import *
which gives the following error
ModuleNotFoundError: No module named '__main__.crypto'; '__main__' is not a package
directory structure:
-module
--__init__.py
--sample.py
--tester.py
Hoping for a solution
Thanks in advance
If they are in the same module, you can directly import the file as given below. Works for me.
sample.py
def myfun():
print("Sample")
tester.py
from sample import myfun
myfun()
Output
$ python3 tester.py
Sample
If I understand you question correctly, you would like to import a python module from another python folder.
I see you already have a __init__.py file that is needed to declare this folder is a python package.
Navigate to the file where you want to import the module.
from root.parent.folder.file import function_name
other way of doing it
import sys
import os
sys.path.append(os.path.abspath("/home/helloworld"))
from helloworld import *
Hope this helps.

python import from sibling folder

I am trying to import a module from a python file that is in a sibling folder. I read several similar questions here and tried to apply solutions listed there, but I wasn't able to solve the problem.
The structure is as follows:
parentfolder/gfolder/codefolder/fileA.py
parentfolder/gfolder/utilfolder/util.py
gfolder, codefolder and utilfolder all have an __init__.py.
I'm trying to do in fileA.py:
import gfolder.utilfolder.util as util
I also tried adding before the import statement:
sys.path.append(".../parentfolder/")
And that didn't work either:
import gfolder.utilfolder.util as util
ModuleNotFoundError: No module named 'gfolder'
The solution in a similar question says to include __init.py__ in the directories, which I already have.
EDIT:
Now both sys.append and sys.insert work and the problem was that I included a slash at the end of the path. When I took it out, everything worked.
First of all, let me describe you the differences between a Python module & a Python package so that both of us are on the same page. โœŒ
A module is a single .py file (or files) that are imported under one import and used. โœ”
import aModuleName
# Here 'aModuleName' is just a regular .py file.
Whereas, a package is a collection of modules in directories that give a package hierarchy. A package contains a distinct __init__.py file. โœ”
from aPackageName import aModuleName
# Here 'aPackageName` is a folder with a `__init__.py` file
# and 'aModuleName', which is just a regular .py file.
Therefore, when we have a project directory named proj-dir of the following structure โคต
proj-dir
--|--__init__.py
--package1
--|--__init__.py
--|--module1.py
--package2
--|--__init__.py
--|--module2.py
๐Ÿ”Ž Notice that I've also added an empty __init__.py into the proj-dir itself which makes it a package too.
๐Ÿ‘ Now, if you want to import any python object from module2 of package2 into module1 of package1, then the import statement in the file module1.py would be
from proj-dir.package2.module2 import object2
# if you were to import the entire module2 then,
from proj-dir.package2 import module2
I hope this simple explanation clarifies your doubts on Python imports' mechanism. ๐Ÿ˜Š
As Andrew Cox answerd int the following thread Import a module from a relative path
You can add the subdirectory to your Python path so that it imports as a normal script
import sys
sys.path.insert(0, <path to gfolder>)
import gfolder
you can also add the directory to the PATH var of the Linux system (I use it while I'm working on a project, at the end i modified the PATH to it's origin value)
if you maintain the following structre than it is working out side the box
parentfolder/gfolder/codefolder/fileA.py
parentfolder/gfolder/utilfolder/util.py
parentfolder/gfolder/main.py
run main.py

'Attempted relative import in non-package' although packages with __init__.py in one directory

I have a module named extended.py which contains the following line:
from .basic import BasicModule
and the file basic.py resides in the same directory as does __init__.py. However, when I try to run it as:
python extended.py
I get the error:
ValueError: Attempted relative import in non-package
Also adding the line:
from __future__ import absolute_import
does not solve the problem.
Maybe I am too tired to see the obvious - but I don't see the problem here.
Relative imports only work for packages, but when you importing in extended.py you are running a top-level module instead.
The current directory may hold a __init__.py file but that doesn't make exended.py part of a package yet.
For something to be considered a package, you need to import the directory name instead. The following would work:
main.py
packagename\
__init__.py
basic.py
extended.py
then in main.py put:
import packagename.extended
and only then is extended part of a package and do relative imports work.
The relative import now has something to be relative to, the packagename parent.

Categories