Search code examples
pythonpackagenameerror

python: NameError: name 'first' is not defined when I import the whole package


When I import the whole package, it gives me a NameError. But when I import individual modules and run the same code, it executes properly.

My structure is:

  • my_package/directory
    • __init__.py
    • first.py
    • second.py
    • main.py

When I run main.py as below, it gives me a NameError:

import my_package
first.say_1st()
second.say_2nd()
"C:\\Program Files\\Python312\\python.exe" "D:\\E Drive\\Training\\pythonProject1\\Sample scripts\\Package example\\main.py"
Traceback (most recent call last):
File "D:\\E Drive\\Training\\pythonProject1\\Sample scripts\\Package example\\main.py", line 4, in \<module\>
first.say_1st()
^^^^^
NameError: name 'first' is not defined. Did you mean: 'list'?

Process finished with exit code 1

But when I run main.py as below, it gives me the expected output.

from my_package import first
first.say_1st()

from my_package import second
second.say_2nd()

Am I doing something wrong?


Solution

  • To install all packages, use from my_package import * instead of just import my_package. I have seen this issue before, and all I can say is Python is a bit funky.

    Hopefully this fixes your issue.