0

I would like to do the following import:

from . import foo.bar.foobar

Why is that a problem for python? Alternatively

from .foo.bar import foobar

does not work either.

The foobar module should be imported from the example.py file as seen in this folder structure:

test/
|____foo/
|    |____bar/
|         |___ __init__.py
|         |___ foobar.py
|
|____core/
     |____ example.py

What works is

sys.path.insert(0, r"../foo/bar")
import foobar

but i wondered if there was another way.

tartearth
  • 29
  • 2
  • Please share your code structure. – Devang Sanghani Feb 11 '22 at 09:04
  • try `from ..foo...` – Lei Yang Feb 11 '22 at 09:07
  • can you share the error you are getting and the directory structure. add `__init__.py` in the directory also to make it work – sahasrara62 Feb 11 '22 at 09:07
  • Please clarify your folder structure and where are you trying to import the module. Which is your current directory? are trying to import from an installed package? – Davide Laghi Feb 11 '22 at 09:08
  • The error for the first methode is `SyntaxError: invalid syntax`. The error for the second method is `ImportError: attempted relative import with no known parent package`. This is not an installed package, but a local repo. – tartearth Feb 11 '22 at 09:42
  • @tartearth Is `example.py` the main script that is being run? If so, relative imports using `.` or `..` will never work - they only work when the file is itself being imported as a module. See [this answer](https://stackoverflow.com/a/14132912/6445069) – Phydeaux Feb 11 '22 at 09:57

1 Answers1

0

My recommendation in your case is to stick to absolute import path in example: from foo.bar import foobar

Then suppose you are in the test folder, you can run your example.py file with the below command:
python -m core.example

This allow you program to know that it should consider the current folder as the source and then the import will work.

Another way out could be to just move example.py directly in test and everything would work fine but it probably don't suit your case.

Ssayan
  • 938
  • 5
  • 12