Why import only at module level?
François Pinard
pinard at iro.umontreal.ca
Thu Feb 19 14:06:02 EST 2004
[Peter Hansen]
> Paul Rubin wrote:
> > That's what the Python style guides advise. They don't seem to like
> > def frob(x):
> > import re
> > if re.search('sdf[234]xyz', x): ...
> > instead preferring that you pollute your module's global namespace
> > with the names of all your imports. What's the point of that?
> Maintainability. It's also well understood that there are potential
> benefits to the approach you show above, late-loading of code being
> one of them (which can improve startup time for certain apps), but
> as maintainability should almost always be the primary consideration,
> the standard advice is to put stuff together at the top where it's
> clear to maintainers which modules are used in the code (in other
> words, what a given module is coupled to).
I never understood this "standard advice", nor how it is related to
maintainability. What makes a module significantly more maintainable
by merely grouping `import' statements at the beginning? What is it so
crucial to know that the `re' module is used, or not, in a program? It
looks like a tiny detail to me.
If for some strange reason I urgently needed to know everything that a
program imports, I guess I would then `grep' the source for the word
`import'i, or just search with an editor! :-) This is surely not a need
I often have, and for from enough for justifying the convention.
If within a `def', I will often use a module which I do not use
elsewhere in a program, there is no reason to make it global. Global
variables should be avoided on the average, and moreover, Python is
faster at accessing a local than a global.
I'm not really crusading for either method, but maybe a bit against
the mere existence of the "standard advice", unless it acquires some
better justification. Of course, "maintainability" is a virtue, but the
relation between maintainability and the "standard advice" is asserted
as if it were to be evident, without explanation.
--
François Pinard http://www.iro.umontreal.ca/~pinard
More information about the Python-list
mailing list