Overview
Example error:
Traceback (most recent call last):
File "main.py", line 2, in <module>
Foo.hello()
NameError: name 'Foo' is not defined
This issue happens when you try to invoke a class within a module without specifying the module.
Initial Steps Overview
Detailed Steps
1) Change the call to reference the module
# foo.py
class Foo():
@staticmethod
def bar():
print("Hello")
# main.py
import foo
Foo.bar() # NameError: name 'Foo' is not defined
Above we see that Foo.bar()
doesn’t work, which is because we only have access to the module foo
and not the class within it. To access this class we could instead do foo.Foo.bar()
. In this case, foo
is the module name and Foo
is the class name.
You would have a similar problem if the casing of the class was the same as the module you would just receive a different error.
2) Change the import to load the class directly
Given the example shown in step #1, the import within main
can be changed to make the call work. We simply need to use the following format from <modulename> import <classname>
. So in our example, this would be:
from foo import Foo
Foo.bar() # This now works
Check Resolution
Your call now works as expected.