-3

I have folder structure like this:

d1
 - app
   — script.py
 - lib
   — lib1
     — file.py

When I do from ..lib.lib1 import my func in script.py it gives error:

SystemError: Parent module '' not loaded, cannot perform relative import

I am using Python 3.

martineau
  • 119,623
  • 25
  • 170
  • 301
Volatil3
  • 14,253
  • 38
  • 134
  • 263
  • You could find that page by pasting the error message in any decent search engine. – vaultah May 04 '17 at 15:58
  • @vaultah and what made you to think I did not try it? I did try but some how I am doing something wrong that it still gives error. – Volatil3 May 04 '17 at 15:59
  • `from ..lib.lib1 import my func` produces a `SyntaxError`. What is your actual `import` statement? It also appears the you're trying to import from a grandparent folder, not the parent folder. – martineau May 04 '17 at 16:09
  • Relative imports only work inside Python packages. Your folder structure doesn't define one. Question [**_How to properly use relative or absolute imports in Python modules?_**](http://stackoverflow.com/questions/3616952/how-to-properly-use-relative-or-absolute-imports-in-python-modules) may help. – martineau May 04 '17 at 16:33
  • Also see the documentation about regular [**Packages**](https://docs.python.org/3/reference/import.html#packages). – martineau May 04 '17 at 16:41
  • @martineau correct, from garandparent folder. – Volatil3 May 04 '17 at 16:47

1 Answers1

0

Relative imports are for use within packages. You could change what you have into one by adding some empty __init__.py files into your directory structure like this:

d1
 - test.py  # added to run script.py below
 - app
   - __init__.py  # an empty script
   — script.py
 - lib
   - __init__.py  # an empty script
   — lib1
     - __init__.py  # an empty script
     — file.py

There's also a new file I've called test.py because you genrally can't run modules within a package as the main script (which is why I added test.py). All it contains is:

from app import script

I also changed the import in script.py to this:

from lib.lib1 import file

To show that the above import works, I put a print('in file.py') in file.py.

Now running test.py, which runs the script module by importing it, produces the following output:

in file.py

Now, if you want to import a particular function from file.py, you could do something like this in script.py:

from lib.lib1.file import my_func
martineau
  • 119,623
  • 25
  • 170
  • 301