Specificity in importing python module?

2019-08-04 05:08发布

问题:

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.

回答1:

Importing serial will result in the creation of all names that the module creates. This sounds self-obvious until you realize that serial 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 importing serial.tools.list_ports also imports serial.tools. It does also import serial, but you should import it explicitly rather than having Python do it for you by accident.

>>> import this
The Zen of Python, by Tim Peters

 ...
Explicit is better than implicit.
 ...