Last updated: Apr 8, 2024
Reading timeยท3 min
The Python "AttributeError module 'serial' has no attribute 'Serial'" occurs
when we have a local file named serial.py
and import from the pyserial
module.
To solve the error, make sure you haven't got a file named serial.py
,
uninstall the serial
module and install pyserial
.
First, make sure you haven't installed the
serial module instead of pyserial
.
# ๐๏ธ Uninstall serial and pyserial pip uninstall serial pip uninstall pyserial pip3 uninstall serial pip3 uninstall pyserial # ๐๏ธ Install pyserial pip install pyserial pip3 install pyserial
Now try importing the serial
module.
import serial ser = serial.Serial('/dev/ttyUSB0') print(ser.name)
serial.py
Make sure you don't have a local file named serial.py
.
serial.py
, it would shadow the third-party pyserial
module.Here is an example of how the error occurs in a local file named serial.py
.
import serial ser = serial.Serial('/dev/ttyUSB0') # โ๏ธ AttributeError: partially initialized module 'serial' has no # attribute 'Serial' (most likely due to a circular import). Did you mean: 'serial'? print(ser.name)
The Python interpreter first looks for the imported module in the built-in modules, then in the current directory, then in the PYTHON PATH, then in the installation-dependent default directory.
It doesn't have to be the file you are running directly. If you have a
serial.py
file anywhere in the directory, it would shadow the official module.
You can access the __file__
property on the imported module to see whether it
is shadowed by a local file.
If your serial
import is shadowed by a local file, the result will look
something similar to the following.
import serial print(serial.__file__) # โ๏ธ The result is shadowed by a local file # /home/borislav/Desktop/bobbyhadz_python/serial.py
If your serial
import is not shadowed by a local file or variable, the result
will look similar to the following.
import serial print(serial.__file__) # โ The result is pulling in the correct module # /home/borislav/Desktop/bobbyhadz_python/venv/lib/python3.10/site-packages/serial/__init__.py
A good way to start debugging is to print(dir(your_module))
and see what
attributes the imported module has.
import serial # โ ['__builtins__', '__cached__', '__doc__', '__file__', # '__loader__', '__name__', '__package__', '__spec__', 'serial'] print(dir(serial))
If you pass a module object to the dir() function, it returns a list of names of the module's attributes.
We can see that the Serial
class is not present in the module's attributes,
which is a clear indication that we are shadowing the third-party module with
our local module.
Make sure you haven't misspelled anything in your import statement as that could also cause the error.
Once you rename your file, you should be able to use the serial
module.
import serial ser = serial.Serial('/dev/ttyUSB0') print(ser.name)
You can learn more about the related topics by checking out the following tutorials: