Each Answer to this Q is separated by one/two green lines.
I have two python modules:
import b def hello(): print "hello" print "a.py" print hello() print b.hi()
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?
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.)
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.
The problem is the circular dependency between the modules.
a. But one of them needs to be loaded first – in this case python ends up initializing module
b.hi() doesn’t exist yet when you try to access it in
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
from package.MyEnumClass import MyEnumClass
Hope that helps someone
I faced the same issue.
fixed by using
import the_module_name from importlib import reload reload(the_module_name)
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.c) were explicitly imported, and assumed that the
import statement actually imported
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
The solution was simply to delete the
.pyc files, and let them be automatically regenerated.
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.
on ubuntu 18.04 ( virtualenv, python.3.6.x), the following reload snippet solved the problem for me:
import my_module # my_module.py from importlib import reload # reload reload(my_module) print(my_module) print(my_modeule.hello())
for more documentation check : here
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
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.
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
You can understand what’s going by adding 2 prints :
print(__name__) import b
print(__name__) import a
$ python3 a.py __main__ b a
a.py ends up being loaded/executed 2 times. one as
__main__ and one as
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.
are you saved ‘b.py’ ?
you must save ‘b.py’ first.
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
The order of the importing was the reason why I was having issues:
############ # 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
from a import ProblemThing class NewThing(ProblemThing): pass
Just another example of how it might look, similar to RichieHindie’s answer, but with classes.
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.
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.
In my case working with python 2.7 with numpy version 1.15.0, it worked with
pip install statsmodels=="0.10.0"