I have two python modules:
a.py
import b def hello(): print "hello" print "a.py" print hello() print b.hi()
b.py
import a def hi(): print "hi"
When I run a.py
, I get:
AttributeError: 'module' object has no attribute 'hi'
What does the error mean? How do I fix it?
To solve the Python "AttributeError: module has no attribute", make sure you haven't named your local modules with names of remote modules, e.g. datetime.py or requests.py and remove any circular dependencies in import statements.
If you are getting an object that has no attribute error then the reason behind it is because your indentation is goofed, and you've mixed tabs and spaces.
Attribute errors in Python are raised when an invalid attribute is referenced. To solve these errors, first check that the attribute you are calling exists. Then, make sure the attribute is related to the object or data type with which you are working.
It's simply because there is no attribute with the name you called, for that Object. This means that you got the error when the "module" does not contain the method you are calling.
You have mutual top-level imports, which is almost always a bad idea.
If you really must have mutual imports in Python, the way to do it is to import them within a function:
# In b.py: def cause_a_to_do_something(): import a a.do_something()
Now a.py can safely do import b
without causing problems.
(At first glance it might appear that cause_a_to_do_something()
would be hugely inefficient because it does an import
every time you call it, but in fact the import work only gets done the first time. The second and subsequent times you import a module, it's a quick operation.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With