Should import be inside or outside a Python class?
Question: # Overview

Suppose I'm building a class for general usage: I might need to import it
wherever, use it in a couple other files, etc. Should the import go before the
class, as:

    
    
    import foo
    
    class Bar():
    
        def __init__(self):
            foo.spam()
    

Or inside the `__init__` method, as:

    
    
    class Bar():
    
        def __init__(self):
    
            import foo
    
            foo.spam()
    

# My Analysis

## Outside

\+ Brings the `foo` into the global namespace for use throughout `Bar`

~~\- Importing`Bar` also requires you to manually import `foo`~~
(@MartijnPieters _et al._)

## Inside

\+ Avoids loading `foo` before you actually need to

\+ `foo` loads when `Bar` is instantiated ~~imported (and used)~~ (@BrenBarn)

\- `foo` is unavailable elsewhere


Answer: Usually all imports go at the top of the module. That makes it easy to see the
dependencies of a module at a glance, either by visual inspection or in a code
checker like pyflakes. Your assumption that "importing `Bar` also requires you
to manually import `foo`" is false.

The only times you would imports inside functions or methods are when the
imports are very resource-intenstive (e.g., slow) or unreliable (e.g.,
optional dependencies that may not be installed, platform-specific modules or
modules that tend to break), and client code is not expected to always call
the functions in question.

