Home > Software design >  How to Import from parent directory Python
How to Import from parent directory Python

Time:02-26

I am trying to import a file from the main directory using python. I tried several methods but no luck :(.

My file directory

|_ api
    |__init__.py
    |_api1.py
    |_api2.py
    |_api3.py
    |_api4.py
    |_api5.py
    |_api6.py
|__init__.py
|_api.py
|_db_ops.py

Challenge

I am trying to import some methods of api.py into api1.py and api2.py.

The solutions I have found were:

1. Add __ini__.py file
   I have added them as you can see but did not work.

2. import using `import api`
   did not worked rather throws an error **ModuleNotFoundError**

3. import using 'from . import api'
   throws an error "cannot import from unknown module"

4. even tried to create a parent folder **test** and then tried with import test.apicall  but still did not worked!

Any help.

Thanks

CodePudding user response:

first of all, the file name is __init__.py and not __ini__.py. by default, you only can import directory from the same level or below where you are using the python command. example:

myproject/
  project/
    __init__.py
    foo.py
  bar.py

if the terminal in myproject and i run python project/foo.py, foo can import bar.py , but if i am myproject/project and i run python foo.py, foo cannot import bar.py

to change the default you can use

import sys
sys.path.append('path of my dir')

CodePudding user response:

It depends on what you want to do. If you want to run a script in a lower-level folder, Python will not let you do it. On the other hand, let's say for simplicity you have the folder structure

mypackage/
   subpackage/
      __init__.py
      api1.py
   __init__.py
   api.py

If api.py looks like the following

def foo(a):
    print(a)

then in api1.py you can have a relative import like

from ..api import foo as f

Then you can't, however, run api1.py as a script, but you can use f as a function to extend things in api1.py or write a script with the content

from mypackage.subpackage.api1 import f

so in that case, it will look like the function foo was in api1.py.

I'll note that this was heavily inspired by the Python-documentation on relative imports... (https://docs.python.org/3/reference/import.html)

  • Related