As a general rule, I group all my imports in the beginning of the module's source, even if it is only used a handful of times by a few functions.
However, on such cases as the import is only needed by specific function(s) zero or once, then I do the import in the function itself. Importing argparse, for example: import sys def api_func(*args, **kwargs): pass def main(args): import argparse # ... api_func() if __name__ == '__main__': sys.exit(main(sys.argv)) ~/santa ~/santa On Thu, Feb 17, 2011 at 1:45 PM, Terry Reedy <tjre...@udel.edu> wrote: > On 2/17/2011 12:27 PM, andrea crotti wrote: > > Well no I wasn't really worried about performances. >> I just thought that if an external module is really almost never used, >> it might make sense to import it only when it's really needed. >> > > If the module is only used in one function and the function may called 0 or > 1 times, them yes, it makes some sense. But as soon as the function is > called multiple times, or the module is used in more than one function, or > someone wants to quickly look at the file to determine its dependencies, > then local imports become more trouble than they are worth. > > For instance, suppose a new maintainer adds a function to the module that > needs something from another module. If all imports are at the top, then it > is trivial to see what imports are already made and whether they need > modification. > > I believe the stdlib used to have some local imports, and might still, for > all I know. PEP 8 is is based on long-term experience with the > multi-maintainer stdlib as well as some stylistic preferences. > > -- > Terry Jan Reedy > > > -- > http://mail.python.org/mailman/listinfo/python-list >
-- http://mail.python.org/mailman/listinfo/python-list