Lets say I have a module called device which contains a class called ConfigureDevice. Lets also say that I have a module called comports which defines my com ports in a class called ComPorts (enum in C).
Now, lets say that the constructor for ConfigureDevice takes an argument called comPorts. The question is, should I import comports at the beginning of the device module or should the code creating ConfigureDevice make this import?
So, should import comports occur here:
# device module
import serialwriter
import comports
class ConfigureDevice:
def __init__(self, comPort):
self.serialWriter = serialwriter.SerialWriter(comPort)
Or should I import it in the code that creates ConfigureDevice, like this:
import device
import comports
...
device.ConfigureDevice(comports.ComPorts.COM_1)
You should generally always put
importat the top of the module, where Python programmers will expect to find it, because then any import errors will happen right when the program starts, instead of happening much later when a function is finally called. We generally only putimportinside a function because (a) we are trying to avoid an awkward import loop among badly-designed modules, or (b) because we want to make a 3rd-party library optional so that you only need it if you call that function.Update: Thank you for the code samples! Beyond my initial advice, that
importalways go at the top of a file, I can additionally now recommend that you remove the import ofcomportfrom your device module because, from what I can see, you never use the module there — I do not see the namecomportanywhere in the device module code. In general, if you try removing animportstatement from a file but the program still runs, the statement did not belong there in the first place. The pyflakes program can help you findimportstatements that are no longer useful as your code evolves.