• Register
1 vote
2.9k views

Problem :

I am very new to Python. Now I am trying to import my function from the another file in a same directory. I am able to do it sometimes with the use of .mymodule import myfunction but most of the times I face below error:

“Importerror: attempted relative import with no known parent package”.

I am unable to understand the above error and also couldn't find any relevant explanation about it. It seems completely random to me. I am looking for someone who is expert in Python and who can help me in fixing above error.

9 6 2
3,980 points

Please log in or register to answer this question.

3 Answers

1 vote

Solution :

I had also faced the same Python error in the past. I also had to spend a lot of time in fixing it. I found a  workaround which is importing with the use of if/else block as shown below:

if __name__ == '__main__':
    from mymodule import as_int
else:
    from .mymodule import as_int

# Exported Add function
def expadd(a, b):
    return as_int(a) + as_int(b)

# Test the function for the module  
def _exptest():
    assert expadd('1', '1') == 2

if __name__ == '__main__':
    _exptest()

If above solution is not working for you and if both of your packages are in the import path (i.e. sys.path), and your module or class you want is in the example/example.py, then to access your class without the relative import you can try:
from example.example import fkt
5 4 2
17,150 points
0 votes

Solution:

unfortunately, this module requires to be within the package, and it also requires to be runnable as a script, occasionally. Any idea how I could achieve that?

It's quite usual to have a layout like this

main.py
mypackage/
    __init__.py
    mymodule.py
    myothermodule.py

.with a mymodule.py like this

#!/usr/bin/env python3

# Exported function
def as_int(a):
    return int(a)

# Test function for module  
def _test():
    assert as_int('1') == 1

if __name__ == '__main__':
    _test()

..a myothermodule.py like this…

#!/usr/bin/env python3

from .mymodule import as_int

# Exported function
def add(a, b):
    return as_int(a) + as_int(b)

# Test function for module  
def _test():
    assert add('1', '1') == 2

if __name__ == '__main__':
    _test()

..and a main.py like this…

#!/usr/bin/env python3

from mypackage.myothermodule import add

def main():
    print(add('1', '1'))

if __name__ == '__main__':
    main()

...which performs fine at the time you run main.py or mypackage/mymodule.py, however fails with mypackage/myothermodule.py, due to the relative import…

from .mymodule import as_int

The way you're inferred to run it is…

python3 -m mypackage.myothermodule

however it's somewhat verbose, and doesn't mix well with a shebang line like #!/usr/bin/env python3.

The easiest solve for this instance, pretending the name mymodule is globally unique, would be to avoid employing relative imports, and just use…

from mymodule import as_int

Though, in case it's not unique, or your package structure is more complex, you'll require to add the directory bearing your package directory in PYTHONPATH, and do it like this…

from mypackage.mymodule import as_int

...or in case you want it to perform "out of the box", you can frob the PYTHONPATH in code first with this…

import sys
import os

PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))

from mypackage.mymodule import as_int

I'm -1 on this and on any other raised twiddlings of the __main__ machinery. The only employ instance appears to be running scripts that occur to be living within a module's directory, which I've always view as an antipattern. To make me change my mind you'd have to convince me that it isn't.

Whether running scripts within a package is an antipattern or not is subjective, however personally I trace it truly helpful in a package I have which comprise few custom wxPython widgets, so I can run the script for any of the source files to display a wx.Frame bearing just that widget for testing purposes.

10 6 4
31,120 points
1 vote

Solution:

Whenever you get an error produced by the interpreter or compiler read it carefully. The error message says all about the cause of encountered error in a nutshell. You are having an ImportError in this case. As you’ve mentioned, you are trying to import a user-defined function from another file within the same directory. Let me give an example. Assume you have a file named foo.py that contains below functions:

def function():
	# do something herea
	return 1
def another_function():
	# do something herea
	return 2

And now, you want to import the file in bar.py as a module to use the functions available in foo.py. You should simply do:

from foo import function, another_function

Yes! It is as simple as this. This has to be work all you need to make sure that the files are in the same directory. Good day!

13 9 6
94,240 points

Related questions

0 votes
1 answer 21 views
21 views
Problem: I want to import a function from another file in the same directory. Sometimes it works for me with from .mymodule import myfunction but sometimes I get a: SystemError: Parent module '' not loaded, cannot perform relative import Sometimes it works with from ... and I couldn't find any explanation. This looks completely random. Could someone explain to me what's the logic behind all this?
asked Jan 26 Mashhoodch 10.2k points
0 votes
1 answer 8 views
8 views
Problem: In core_test.py I have the following import statement from ..components.core import GameLoopEvents However, when I run, I get the following error: tests$ python core_test.py Traceback (most recent call last): File "core_test.py", line 3, in <module> from ..components.core import GameLoopEvents ValueError: Attempted relative import in non-package
asked Feb 23 Mashhoodch 10.2k points
0 votes
1 answer 11 views
11 views
Probelm: parent module '' not loaded, cannot perform relative import.
asked Feb 17 charles mathews 3.8k points
0 votes
1 answer 814 views
814 views
Problem : While trying to import the OpenCV, using import cv2 I facing the below error: /usr/local/lib/python2.7/dist-packages/cv2/__init__.py in <module>() 12 13 # make IDE's (PyCharm) autocompletion happy ----> 14 from .cv2 import * 15 16 # wildcard import ... - I am trying to play around with the Google's new Colaboratory tool. Please let me know if someone have solution for the above issue.
asked Dec 18, 2019 alecxe 7.5k points
0 votes
2 answers 103 views
103 views
Problem : I have recently installed the cuda 8.0 and cuda 9.0 in the Gpu support system. I encountered the below error while importing from the keras module. It says it is unable to load the native tensorflow runtime. I have received the error log as below: Traceback ... is, Cuda compilation tools, release 8.0, V8.0.61 Is it the clash between two cuda versions? Have anyone solved this before?
asked Feb 18, 2020 mphil 2.3k points
0 votes
1 answer 23 views
23 views
Problem: attributeerror: 'series' object has no attribute 'reshape'
asked Feb 18 charles mathews 3.8k points
1 vote
2 answers 3.2K views
3.2K views
Problem : I am very new to Python. Currently I have one textfile and now I am trying to load it and then want to make the list which should contain each and every line from the text file. I have already tried to use the split() procedure. But I am facing ... I have already wasted a lot of time in understanding and finding workaround for above error.So I am looking for the quick fix on above error.
asked Apr 8, 2020 morrisBson 3.2k points
0 votes
1 answer 2 views
2 views
Problem: How to Solve this : what does import * mean in python HELP! I need help understanding this : what does import * mean in python Can someone please help solve this, I am new in python().
asked 1 day ago Mashhoodch 10.2k points
0 votes
1 answer 863 views
863 views
Problem : I learning Python with the help of free online Python tutorial which wants me to write following Program: Create a temperature converter which will convert Fahrenheit values to Celsius and vice-versa using the following two formulas which relate the temperature f in Fahrenheit to ... ,sep ='') if inputString[-1] == 'F': farenheit = inputDigit print(celsiusConvert(farenheit),'C', sep='')
asked Nov 21, 2019 peterlaw 6.9k points
0 votes
1 answer 313 views
313 views
when I am running this code i get an import errror import numpy as np import os import six.moves.urllib as urllib import sys import tarfile import tensorflow as tf import zipfile from collections import defaultdict from io import StringIO from matplotlib import ... recent call last): File "test.py", line 31, in from utils import label_map_util ImportError: cannot import name 'label_map_util'
asked Oct 25, 2020 psandprop 2.4k points