AttributeError: 'module' object has no attribute

Are you getting this type of error in your Python program?
AttributeError: 'module' object has no attribute 'whatever' ? 
Well, then you might need to change the name of your python file.

For example, save the following code in a file named json.py :
 
import json
print json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])

Then try to run it, and you will get this error :

$ python json.py 
Traceback (most recent call last):
  File "json.py", line 1, in 
    import json
  File "/home/work/practice/json.py", line 3, in 
    print json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
AttributeError: 'module' object has no attribute 'dumps'

But of course the json module has 'dumps' attribute! What went wrong?

When you wrote import json, it tries to find the file json.py in the current directory first and it got the file that you wrote (you saved the file as json.py) and it surely doesn't have any attribute (variable or method) named dumps. All you need to do is to change your filename.

So, the lesson is, don't name your python program such a way that it matches a module name used in your program. Happy coding. :)

Comments

Unknown said…
I mostly get this error but I never fount out the reason behind it.This post was very much insightful. :)

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code