0

main.py:

import second
from second import *

print(second.a)

second.py:

a = "testA"
b = "testB"

Error:

AttributeError: module 'second' has no attribute 'a'

Importing wasn't working on a more complex program. Tried to test it simply and it's not working.

Inside the project folder, there are the other .py files as well as a __pycache__ folder

Doing ↓ doesn't work either:

from second import a, b
  • 1
    Problems like this are often due to the import path order being not what you think it is. You can try printing `second.__file__` to see where it is imported from. – Lev Levitsky May 23 '22 at 14:55
  • I get -- c:\VS Code Workspace\PROJECT\second.py -- The PROJECT folder is the same as main.py – PHGLPagani May 23 '22 at 15:09
  • Your code works for me. Maybe try `print(dir(second))` and see what you have there. Also, as you have `from second import *`, does `print(a)` work? – Yevhen Kuzmovych May 23 '22 at 15:25
  • `print(dir(second))` gives ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__'] AND `print(a)` gives `NameError: name 'a' is not defined` – PHGLPagani May 23 '22 at 15:34
  • can you remove the import second from main.py and try again and use print(a) – Nitin Priyadarshi May 23 '22 at 16:22
  • I still get `NameError: name 'a' is not defined` – PHGLPagani May 23 '22 at 19:35

2 Answers2

0

Your code works for me as well. I think it maybe caused by your .pyc file which you run your code before.

Delete .pyc file in your package and rerun your code.

Or you can try running your code in a new environment.

MingJie-MSFT
  • 5,569
  • 1
  • 2
  • 13
0

I figured it out!

The answer was quite simple, and it was to create a virtual environment.

The following helped me:

VIDEO

STACK

I appreciate all the help!