2

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)
Nakilon
  • 34,866
  • 14
  • 107
  • 142
Baz
  • 12,713
  • 38
  • 145
  • 268
  • possible duplicate of [Python import coding style](http://stackoverflow.com/questions/477096/python-import-coding-style) – DhruvPathak Oct 10 '11 at 12:32

1 Answers1

5

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.

Brandon Rhodes
  • 83,755
  • 16
  • 106
  • 147
  • Thanks Brandon. I've added two examples to make my question more clear. In both examples the import is at the top, but which is correct? – Baz Oct 10 '11 at 12:44