7

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?

Noctis Skytower
  • 21,433
  • 16
  • 79
  • 117

3 Answers3

3

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.

Serjik
  • 10,543
  • 8
  • 61
  • 70
-1

you only require to import only module a.

import a
Dharmesh Fumakiya
  • 2,276
  • 2
  • 11
  • 17
-1

Use import .a or, better, import st.a. These will only work if you are importing tb as part of your package (e.g. using python -m switch from parent directory) rather than running it like a script.

As others have said, simplyimport a will work. This has to advantage of working regardless of whether st is run as a module or script, but it's bad practice and only works on python 2, not python 3.

The same applies to the from variants that others have mentioned.

Arthur Tacca
  • 8,833
  • 2
  • 31
  • 49