Module has no attribute
Lastmod: 2023-01-26

Overview

Example error:

python main.py
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    foo.bar()
AttributeError: module 'foo' has no attribute 'bar'

This issue happens when you try to invoke a class within a module without specifying the module.

Initial Steps Overview

  1. Call the class directly

  2. Change import to load the class directly

Detailed Steps

1) Call the class directly

# foo.py
class foo():
  @staticmethod
  def bar():
    print("Hello")

# main.py
import foo

Given the above code a call to foo.bar() within main.py would result in an error about the module ‘foo’ not having the attribute ‘bar’. This is because we have only made the module accessible and not it’s class foo. So to call it we could instead do foo.foo.bar() with the first foo being the module name and the second being the class name.

2) Change import to load the class directly

If we change the import from step 1 to instead be from <modulename> import <classname> this will make the class foo directly accessible, eg:

# main.py
from foo import foo
foo.bar() # This now works!

Check Resolution

Your call to the method should now work as expected.

Further Information

Authors

@gerry

comments powered by Disqus