chevron_left
933 points
8 4 2

Problem :

I am very new to Python. Now I am trying to import my function from another file in the same directory. I am able to do it sometimes with the use of the .mymodule import function but most of the times I face the 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 an expert in Python and who can help me in fixing the above error.

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 the 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

More Posts

ImportError: cannot import name _remove_dead_weakref Naymul01 - Oct 17
Invalid syntax python for no reason Naymul01 - Oct 19
Attributeerror: 'str' object has no attribute 'sort' Naymul01 - Oct 19
In python, math expressions are evaluated from left to right, no matter what the operators are. Naymul01 - Oct 19
Module 'scipy' has no attribute 'optimize' Naymul01 - Oct 18
invalid syntax python for no reason sam_dev - Sep 20
“AttributeError: module has no attribute” or “ImportError: cannot import name” Farkhanda Athar - Apr 8, 2020
Number of occurrences of a character in a string in python with example. Tania - Sep 13
Develop a shopping cart website with django 2 and python 3. Tania - Sep 13
Data Structure and Algorithmic Thinking with Python by Narasimha Karumanchi pdf Tasnia Sultana - May 7