I've been working with the PySerial library for pythonPyserial API, and I can't seem to understand why I have to specifically import a certain part of the module.
This will give me an error:
import serial
for item in serial.tools.list_ports.comports():
print item
The above snippet will return "AttributeError: type object 'Serial' has no attribute 'tools'"
If I import that attribute specifically, I get no errors:
import serial.tools.list_ports
for item in serial.tools.list_ports.comports():
print item
Can someone help me understand why the first import won't run the comports() method?
I understand that importing fewer items into memory is a best practice, but I'm also using other methods from the PySerial module. It seems redundant to import both serial and serial.tools.list_ports.
Importing
serial
will result in the creation of all names that the module creates. This sounds self-obvious until you realize thatserial
does not create any attribute called "tools" within it. This is in fact a separate module.import
does you the favor of importing parent modules, which is why importingserial.tools.list_ports
also importsserial.tools
. It does also importserial
, but you should import it explicitly rather than having Python do it for you by accident.