[Tutor] import statements in functions?

Alan Gauld alan.gauld at freenet.co.uk
Tue Mar 22 00:12:52 CET 2005


> Is there a convention to be considered for deciding if import
> statements should be included in a function body?

The convention is for all imports to be at the top of a module.

>      def specialFunction():
>           import foo_special
>           doSomethingSpecial()

BUt I copnfess I do occasionally use this form under certain
conditions, see below...

> Also, does the choice have any impact on performance/space/etc.?

Marginally, because imports do take some time. If the import is not
normally going to be needed hiding it inside a function definition
can save a little bit of time.

> will the import function get called each time (and possibly ignored)
> in the second version?

Yes it will but because Python has already seen it it will not be
a big impact - especially if the function is itself rarely used.

> The reason I consider the second form is that the module foo_special
> is only used by the code in specialFunction(), and detracts (IMHO)
> from understanding the rest of the code in the module.

And thats exactly when I would use the embedded import
- it hides some complexity,
- slightly increases performamnce and
- has little impact when called becauiuse such calls are rare.

A personal perspective :-)

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list