I have a directory with a number of .py
files in it. each file defines some classes. I also have an empty __init__.py
in the directory.
For example:
myproject __init__.py mymodule __init__.py api.py models.py views.py
I am trying to import mymodule
and access the classes defined in all these files:
from myproject import mymodule print mymodule.api.MyClass
It gives me an error saying that mymodule
has no attribute api
. Why? And why I can access just one of the files (models.py
) and not the others?
In [2]: dir(banners) Out[2]: ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'models']
What does it mean when a module has no attribute? 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.
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.
The Python "AttributeError: 'list' object has no attribute" occurs when we access an attribute that doesn't exist on a list. To solve the error, access the list element at a specific index or correct the assignment.
The Python "AttributeError: 'str' object has no attribute" occurs when we try to access an attribute that doesn't exist on string objects. To solve the error, make sure the value is of the expected type before accessing the attribute. Here is an example of how the error occurs. main.py.
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. Run the script with python -tt to verify.
AttributeError can be defined as an error that is raised when an attribute reference or assignment fails. For example, if we take a variable x we are assigned a value of 10. In this process suppose we want to append another value to that variable. It's not possible.
The problem is submodules are not automatically imported. You have to explicitly import the api
module:
import myproject.mymodule.api print myproject.mymodule.api.MyClass
If you really insist on api
being available when importing myproject.mymodule
you can put this in myproject/mymodule/__init__.py
:
import myproject.mymodule.api
Then this will work as expected:
from myproject import mymodule print mymodule.api.MyClass
If you are an idiot, like me, then also check whether you didn't name your python file the same as the module you are trying to import.
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