Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import one submodule from different submodule? [duplicate]

My project has the following structure:

DSTC/
    st/
        __init__.py
        a.py
        g.py
        tb.py
    dstc.py

Here is a.py in part:

import inspect
import queue
import threading

Here is tb.py in part:

import functools
from . import a

When run directly, a.py produces no errors, and it is easy to verify there were no SyntaxErrors. However, running tb.py causes the following error:

"C:\Program Files\Python36\python.exe" C:/Users/user/PycharmProjects/DSTC/st/tb.py
Traceback (most recent call last):
  File "C:/Users/user/PycharmProjects/DSTC/st/tb.py", line 15, in <module>
    from . import a
ImportError: cannot import name 'a'

Process finished with exit code 1

How should I rewrite the import of a from tb so that tb can be run directly without causing errors?

like image 958
Noctis Skytower Avatar asked Sep 20 '17 16:09

Noctis Skytower


1 Answers

Either you can use

import a

or relative

from .a import *

and in this case module **a** should be loaded

python -m a tb.py

will works for you.

import * is discouraged, import just as you need

If you got a main.py in your DSTC as follows:

#  main.py
from st import tb

and you run main.py only relative approach will work for you

# tb.py 
import a  # will not work
from .a import * # will work

because this time you load 'a' as a module.

like image 160
Serjik Avatar answered Nov 16 '22 10:11

Serjik