0
helloPython
  __init__.py
  
  myutil
    __init__.py
    mymaths.py

  service
    __init__.py
    cal.py

mymaths.py

def myadd(a, b):
    return a+b

cal.py

from ..myutil import mymaths #or any other similar import statement

sum = mymaths.myadd(3, 4)

Here, in cal.py, I want to use a method defined in mymaths.py as above However when I try to import, I get below error, when I "Run Python file in terminal" in VSCode Tried multiple ways

  1. First method

    from ..myutil import mymaths

ImportError: attempted relative import with no known parent package

  1. Second method

    from helloPython.myutil import mymaths

ModuleNotFoundError: No module named 'helloPython'

martineau
  • 119,623
  • 25
  • 170
  • 301
michael
  • 661
  • 1
  • 7
  • 18
  • 1
    Might be helpful: [Relative imports in Python 2.7](https://stackoverflow.com/questions/14132789/relative-imports-in-python-2-7) – martineau Aug 28 '20 at 17:45
  • Thanks, I'm still trying to understand what is script and module. Seems the concept is not that simple to grasp. In java, I can just do import com.package.class from any class from any packages/subpackage and the main() function gets executed. Coming from the java background, I still cannot convince myself that I understood python imports and relative import or anything related to import. This should be the most basic concept for any programming language and I see like hundreds and thousands of questions on python only on **import** – michael Aug 28 '20 at 18:26
  • VSCode is likely complicating the situation, since how it executes the code may be affecting your results. – martineau Aug 28 '20 at 18:28
  • 1
    @napuzba Thanks a lot, I got your article link from somewhere. Read and tried it. It's very well explained – michael Sep 01 '20 at 16:13

1 Answers1

1

Relative imports in Python 2.7 and ImportError: attempted relative import with no known parent package helped me to understand. Thanks to @napuzba and @martineau

michael
  • 661
  • 1
  • 7
  • 18