I'm using libusb1 and noticed an import error when there is a platform module in my main module:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/duranda/.local/lib/python3.6/site-packages/usb1/__init__.py", line 61, in <module>
from . import libusb1
File "/home/duranda/.local/lib/python3.6/site-packages/usb1/libusb1.py", line 199, in <module>
libusb = _loadLibrary()
File "/home/duranda/.local/lib/python3.6/site-packages/usb1/libusb1.py", line 161, in _loadLibrary
system = platform.system()
AttributeError: module 'platform' has no attribute 'system'
This can be easily reproduced by launching a Python interpreter from a directory containing a platform.py or platform/__init__.py and then importing usb1 using import usb1.
How is it possible that a local module shadows another module (in this case the platform module from the standard lib) from a third party module? To the best of my knowledge, libusb1 imports platform directly and doesn't do anything crazy with globals.
add as first lines in your module:
import sys
print("\n".join(sys.path))
import platform
print("platform file is", platform.__file__)
This will probably show that the python path tries to first import your local modules and only then the system modules.
In other words, don't use local modules with names that conflict with system or third party module names.
If multiple modules import a module with the same name, then python imports the module only once.
Only the first import imports the module.
The second import will just point to the already imported module, which it will find in sys.modules
Thus a module name can be considered a unique pointer to python code.
(Try printing out sys.modules. This is a dict and will show you which modules are imported so far.)
So it doesn't matter whether an import statement is located in your file or in a third party file.
import platform will only point to one module. The one that is selected / found is the one that occurs first in the python path.
So self written modules should not have conflicting names with existing modules.
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