Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: 'module' object has no attribute

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?

like image 295
Stephen Hsu Avatar asked Aug 08 '09 23:08

Stephen Hsu


People also ask

How do I fix module object has no attribute?

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.

Why am I getting AttributeError object has no attribute?

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.

How do I fix No attribute error in Python?

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.

What does module has no attribute mean?

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.


1 Answers

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.)

like image 106
RichieHindle Avatar answered Oct 13 '22 21:10

RichieHindle