1

I have spent so many hours trying out different answers on stack overflow that i no longer know what exactly is the proper way to use relative imports. Keep in mind this import should work on localhost and on a server

My project structure enter image description here

init.py enter image description here

Attempts to import Authenticate class in main.py result into ImportError: attempted relative import with no known parent package enter image description here

Kindly give an explanation or links with working examples of importing in the same directory.

Anjayluh
  • 1,647
  • 1
  • 13
  • 22

1 Answers1

3

You are trying to import a Jupyter Notebook, not a class. This is why you get the ImportError.

Have a look at this: ipynb import another ipynb file

If you do not want to import from a Jupyter Notebook but from a module in a specified path you can try this:

import importlib.util
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.MyClass()

You can also use relative import:

from foo import bar

Another option is to add a path to sys.path (over using import) to simplify things when importing more than one module from a single package:

import sys
# my_package dir contains mod_one.py, mod_two.py and mod_three.py
sys.path.append('/foo/bar/my_package')

from mod_one import foo
from mod_two import bar
from mod_three import foobar
nico9T
  • 2,496
  • 2
  • 26
  • 44