I can't import module from other folders

Viewed 54

I can't import all of functions from own module in other directory

my project structure:

/
|-code
    |-db_orm
        |-__init__.py
        |-db_interface.py
    |-streamlit
        |-pages
            |-subpage1.py
            |-subpage2.py
        |-main.py

i want to add functions from db_interface.py module into subpage1.py & subpage2.py file with this code:

from db_orm.db_interface import *

but i can't do it !
i am using VS Code and python 3.9.13
thanks for any help.

1 Answers

A manual option to import modules from other directories is SourceFileLoader.
Not following the from syntax, but a quick solution for e.g. brief trials:

from importlib.machinery import SourceFileLoader

db_interface = SourceFileLoader("db_interface",">YourSystemPath</db_interface.py").load_module()

# call
db_interface.foo()  # foo being a function in db_interface

Note: >YourSystemPath< can be absolute or relative.


If you want to keep the calls only on the functions you could add further functions in between:

def foo():
    db_interface.foo()


foo()

Again that will get messy for larger projects but is a quick workaround.

Related