I have a module that defines a class which instantiates a class from one of two (or more) other modules. Below are a couple of code examples. In the first example, two modules are imported, but only one is used (one per instance of MyIo). In the second example, only the required module is imported. There may be one or more instances of MyIo in a higher level module.
I like that the second example only imports what is used, but I don’t really like that the import is taking place in a ‘code execution’ section.
My questions are:
- Which of the examples is a better architectural choice, and why?
- Is there a penalty for importing modules that are not eventually
used? - Are imports in code execution sections in Python considered ‘bad form?’
This example imports both modules, but only uses one…
''' MyIo.py '''
...
...
from DevSerial import Device as DeviceSerial
from DevUSB import Device as DeviceUSB
class MyIo:
def __init__(self, port)
if port.lower() == 'usb':
self.device=DeviceUSB()
else:
self.device=DeviceSerial(port)
...
...
The following imports only the module being used…
''' MyIo.py '''
...
...
class MyIo:
def __init__(self, port)
if port.lower() == 'usb':
from DevUSB import Device
self.device=Device()
else:
from DevSerial import Device
self.device=Device(port)
...
...
As per PEP 8, all imports should be together at the top of the file. Having them spread throughout the file leads to hard to maintain and debug software.
The only performance overhead I can think of is at program startup – it has to load more modules. Once the program is running there shouldn’t be any extra overhead.
To answer your questions: