Is it pythonic to import inside functions? Is it pythonic to import inside functions? python python

Is it pythonic to import inside functions?


In the long run I think you'll appreciate having most of your imports at the top of the file, that way you can tell at a glance how complicated your module is by what it needs to import.

If I'm adding new code to an existing file I'll usually do the import where it's needed and then if the code stays I'll make things more permanent by moving the import line to the top of the file.

One other point, I prefer to get an ImportError exception before any code is run -- as a sanity check, so that's another reason to import at the top.

I use pyChecker to check for unused modules.


There are two occasions where I violate PEP 8 in this regard:

  • Circular imports: module A imports module B, but something in module B needs module A (though this is often a sign that I need to refactor the modules to eliminate the circular dependency)
  • Inserting a pdb breakpoint: import pdb; pdb.set_trace() This is handy b/c I don't want to put import pdb at the top of every module I might want to debug, and it easy to remember to remove the import when I remove the breakpoint.

Outside of these two cases, it's a good idea to put everything at the top. It makes the dependencies clearer.


Here are the four import use cases that we use

  1. import (and from x import y and import x as y) at the top

  2. Choices for Import. At the top.

    import settingsif setting.something:    import this as fooelse:    import that as foo
  3. Conditional Import. Used with JSON, XML libraries and the like. At the top.

    try:    import this as fooexcept ImportError:    import that as foo
  4. Dynamic Import. So far, we only have one example of this.

    import settingsmodule_stuff = {}module= __import__( settings.some_module, module_stuff )x = module_stuff['x']

    Note that this dynamic import doesn't bring in code, but brings in complexdata structures written in Python. It's kind of like a pickled piece of dataexcept we pickled it by hand.

    This is also, more-or-less, at the top of a module


Here's what we do to make the code clearer:

  • Keep the modules short.

  • If I have all my imports at the top of the module, I have to go look there to determine what a name is. If the module is short, that's easy to do.

  • In some cases having that extra information close to where a name is used can make the function easier to understand. If the module is short, that's easy to do.