[Yum] code cleanup: one function in one source
Michael Stenner
mstenner at phy.duke.edu
Sun Jul 14 14:19:26 UTC 2002
On Sun, Jul 14, 2002 at 01:12:47PM +0300, Vladimir Bormotov wrote:
> and, please, no import inside functions (look at 'import rpm' in this grep
> output and many-many-many import string/os/sys/etc in other sources)...
>
> PythonStyleGuide (http://www.python.org/peps/pep-0008.html):
>
> Imports
> - Imports are always put at the top of the file, just after any
> module comments and docstrings, and before module globals and
> constants.
I'm not going to defend the yum examples specifically, because I
haven't even looked at them, but I feel strongly that this should not
be interpreted as an absolute rule. I agree that it usually makes
code much more readable, and that is good. However, there are some
situations which outrank that benefit.
1) In some cases, the program may not know until runtime if certain
modules will be present.
An example is a cross-platform program that has a copy_file
function. On windows/unix, you use the copy function from the
shutil module. On a mac, you use the copy function from
macostools. macostools doesn't exist on a linux install, so you
can't just import it at the top of a file.
Sure, you could try and import the module and catch the exception,
but I think it's cleaner to determine what platform you're on, and
then import the appropriate modules and set up the functions
appropriately.
2) Efficiency. If there is a function that needs some heavy modules,
but will rarely be called (ie only when the program is being
invoked in some weird mode), then it may make sense to import from
within that function. This way, the modules are never loaded if
they're not needed. This is similar to Just In Time interpretation
in a number of ways.
Python is very good about efficiently dealing with re-imports (it
doesn't just import it again) so function/class level imports have
little cost except readability. Even there, it sometimes ADDS
readability in that it says "most of this module doesn't use string
and re, just this function/class does".
Again, I'm not commenting on the specific yum cases, and I do like the
general rule. I'd guess that 98% or more of my imports appear at the
top of modules. I just don't like it as a universal rule.
-Michael
--
Michael Stenner Office Phone: 919-660-2513
Duke University, Dept. of Physics mstenner at phy.duke.edu
Box 90305, Durham N.C. 27708-0305
More information about the Yum
mailing list