FSeed
FSeed

Reputation: 41

Python how to use absolute import

I have a file structure like this:

My_Package/
    __init__.py
    helper_fun.py
    sub_dir_1/
        __init__.py
        codes.py

I want to import functions from helper_fun.py while inside codes.py. I tried

from helper_fun import foo
from .helper_fun import foo
from ..helper_fun import foo
from My_package.helper_fun import foo

but none works. How should I use absolute import to always specify import directories from the top-level My_Package?

Upvotes: 0

Views: 49

Answers (1)

Diewyns
Diewyns

Reputation: 11

Not quite an answer but you can use :

 import os,sys,inspect
    currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
    parentdir = os.path.dirname(currentdir)
    sys.path.insert(0,parentdir) 

 import helper_fun

From : Importing modules from parent folder

Upvotes: 1

Related Questions