AttributeError: 'module' object has no attribute

PythonAttributeerror

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

I have also seen this error when inadvertently naming a module with the same name as one of the standard Python modules. E.g. I had a module called commands which is also a Python library module. This proved to be difficult to track down as it worked correctly on my local development environment but failed with the specified error when running on Google App Engine.

Solution 3 - Python

The problem is the circular dependency between the modules. a imports b and b imports a. But one of them needs to be loaded first - in this case python ends up initializing module a before b and b.hi() doesn't exist yet when you try to access it in a.

Solution 4 - Python

I got this error by referencing an enum which was imported in a wrong way, e.g.:

from package import MyEnumClass
# ...
# in some method:
return MyEnumClass.Member

Correct import:

from package.MyEnumClass import MyEnumClass

Hope that helps someone

Solution 5 - Python

I faced the same issue. fixed by using reload.

import the_module_name
from importlib import reload
reload(the_module_name)

Solution 6 - Python

I ran into this problem when I checked out an older version of a repository from git. Git replaced my .py files, but left the untracked .pyc files. Since the .py files and .pyc files were out of sync, the import command in a .py file could not find the corresponding module in the .pyc files.

The solution was simply to delete the .pyc files, and let them be automatically regenerated.

Solution 7 - Python

I experienced this error because the module was not actually imported. The code looked like this:

import a.b, a.c

# ...

something(a.b)
something(a.c)
something(a.d)  # My addition, which failed.

The last line resulted in an AttributeError. The cause was that I had failed to notice that the submodules of a (a.b and a.c) were explicitly imported, and assumed that the import statement actually imported a.

Solution 8 - Python

All the above answers are great, but I'd like to chime in here. If you did not spot any issue mentioned above, try clear up your working environment. It worked for me.

Solution 9 - Python

Circular imports cause problems, but Python has ways to mitigate it built-in.

The problem is when you run python a.py, it runs a.py but not mark it imported as a module. So in turn a.py -> imports module b -> imports module a -> imports module b. The last import a no-op since b is currently being imported and Python guards against that. And b is an empty module for now. So when it executes b.hi(), it can't find anything.

Note that the b.hi() that got executed is during a.py -> module b -> module a, not in a.py directly.

In your specific example, you can just run python -c 'import a' at top-level, so the first execution of a.py is registered as importing a module.

Solution 10 - Python

on ubuntu 18.04 ( virtualenv, python.3.6.x), the following reload snippet solved the problem for me:

main.py

import my_module  # my_module.py
from importlib import reload # reload 
reload(my_module)

print(my_module)
print(my_modeule.hello())

where:

|--main.py    
|--my_module.py

for more documentation check : here

Solution 11 - Python

For me, the reason for this error was that there was a folder with the same name as the python module I was trying to import.

|-- core  <-- empty directory on the same level as the module that throws the error
|-- core.py

And python treated that folder as a python package and tried to import from that empty package "core", not from core.py.

Seems like for some reason git left that empty folder during the branches switch

So I just removed that folder and everything worked like a charm

Solution 12 - Python

You can understand what's going by adding 2 prints :

a.py :

print(__name__)
import b

b.py :

print(__name__)
import a

Then:

$ python3 a.py
__main__
b
a

so a.py ends up being loaded/executed 2 times. one as __main__ and one as a.

Solution 13 - Python

In some cases it could be simply that the file is saved in the right directory but the python written on the file is not yet saved when writing it on the virtual environment. So when python imports a.py to b.py there is no code imported. It's blank in other terms. Seems like a easy to identify error that I see often. It's worth checking. -Cody

Solution 14 - Python

are you saved 'b.py' ? you must save 'b.py' first.

Solution 15 - Python

Not sure how but the below change sorted my issue:

i was having the name of file and import name same for eg i had file name as emoji.py and i was trying to import emoji. But changing the name of file solved the issue .

Hope so it helps

Solution 16 - Python

The order of the importing was the reason why I was having issues:

a.py:

############
# this is a problem
# move this to below
#############
from b import NewThing

class ProblemThing(object):
    pass

class A(object):
   ###############
   # add it here
   # from b import NewThing
   ###############
   nt = NewThing()
   pass

b.py:

from a import ProblemThing

class NewThing(ProblemThing):
    pass

Just another example of how it might look, similar to RichieHindie's answer, but with classes.

Solution 17 - Python

I have crossed with this issue many times, but I didnt try to dig deeper about it. Now I understand the main issue.

This time my problem was importing Serializers ( django and restframework ) from different modules such as the following :

from rest_framework import serializers

from common import serializers as srlz
from prices import models as mdlpri

# the line below was the problem 'srlzprod'
from products import serializers as srlzprod

I was getting a problem like this :

from product import serializers as srlzprod
ModuleNotFoundError: No module named 'product'

What I wanted to accomplished was the following :

class CampaignsProductsSerializers(srlz.DynamicFieldsModelSerializer):
    bank_name = serializers.CharField(trim_whitespace=True,)
    coupon_type = serializers.SerializerMethodField()
    promotion_description = serializers.SerializerMethodField()
    
    # the nested relation of the line below
    product = srlzprod.ProductsSerializers(fields=['id','name',],read_only=True,)

So, as mentioned by the lines above how to solve it ( top-level import ), I proceed to do the following changes :

# change
product = srlzprod.ProductsSerializers(fields=['id','name',],read_only=True,)
# by 
product = serializers.SerializerMethodField()

# and create the following method and call from there the required serializer class
def get_product(self, obj):
        from products import serializers as srlzprod
        p_fields = ['id', 'name', ]
        return srlzprod.ProductsSerializers(
            obj.product, fields=p_fields, many=False,
        ).data

Therefore, django runserver was executed without problems :

./project/settings/manage.py runserver 0:8002 --settings=settings_development_mlazo
Performing system checks...

System check identified no issues (0 silenced).
April 25, 2020 - 13:31:56
Django version 2.0.7, using settings 'settings_development_mlazo'
Starting development server at http://0:8002/
Quit the server with CONTROL-C.

Final state of the code lines was the following :

from rest_framework import serializers

from common import serializers as srlz
from prices import models as mdlpri

class CampaignsProductsSerializers(srlz.DynamicFieldsModelSerializer):
    bank_name = serializers.CharField(trim_whitespace=True,)
    coupon_type = serializers.SerializerMethodField()
    promotion_description = serializers.SerializerMethodField()
    product = serializers.SerializerMethodField()

    class Meta:
        model = mdlpri.CampaignsProducts
        fields = '__all__'

    def get_product(self, obj):
        from products import serializers as srlzprod
        p_fields = ['id', 'name', ]
        return srlzprod.ProductsSerializers(
            obj.product, fields=p_fields, many=False,
        ).data

Hope this could be helpful for everybody else.

Greetings,

Solution 18 - Python

SoLvEd

Python is looking for the a object within your a.py module.

Either RENAME that file to something else or use

from __future__ import absolute_import 

at the top of your a.py module.

Solution 19 - Python

In my case working with python 2.7 with numpy version 1.15.0, it worked with

pip install statsmodels=="0.10.0"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStephen HsuView Question on Stackoverflow
Solution 1 - PythonRichieHindleView Answer on Stackoverflow
Solution 2 - PythonlucrussellView Answer on Stackoverflow
Solution 3 - PythonsthView Answer on Stackoverflow
Solution 4 - PythonStoyanView Answer on Stackoverflow
Solution 5 - PythonJustWeView Answer on Stackoverflow
Solution 6 - PythoncraqView Answer on Stackoverflow
Solution 7 - PythonDag HøidahlView Answer on Stackoverflow
Solution 8 - PythonJianView Answer on Stackoverflow
Solution 9 - PythonHot.PxLView Answer on Stackoverflow
Solution 10 - PythonBehzad SezariView Answer on Stackoverflow
Solution 11 - PythonDimaDKView Answer on Stackoverflow
Solution 12 - PythongstView Answer on Stackoverflow
Solution 13 - PythonCody BlombergView Answer on Stackoverflow
Solution 14 - PythonKBT K.B.TView Answer on Stackoverflow
Solution 15 - PythonMD5View Answer on Stackoverflow
Solution 16 - PythonjmunschView Answer on Stackoverflow
Solution 17 - PythonManuel LazoView Answer on Stackoverflow
Solution 18 - Pythonhassanzadeh.sdView Answer on Stackoverflow
Solution 19 - PythonMondaaView Answer on Stackoverflow