开发者

Where to import modules

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 import at 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 put import inside 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 import always go at the top of a file, I can additionally now recommend that you remove the import of comport from your device module because, from what I can see, you never use the module there — I do not see the name comport anywhere in the device module code. In general, if you try removing an import statement from a file but the program still runs, the statement did not belong there in the first place. The pyflakes program can help you find import statements that are no longer useful as your code evolves.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜