Tom Tom - 12 days ago 6
Python Question

Keep imported modules from showing up in code completion?

How can I keep imported modules from being accessible (i.e., clogging my code-completion options)?

For example:

# testmodule.py

import os

def o_stuff():
return


When I import
testmodule
, I don't want
os
to show up every time I type
testmodule.
; I only want the functions/classes declared within testmodule – in this case, just
o_stuff
.

Is there something similar to the asterisk (i.e.,
from testmodule import *
) that will do this?

Answer

You can define a special variable __all__ containing a list of the names to be imported by from module import * - for example:

# testmodule.py

import os

__all__ = ['o_stuff', 'more_stuff']

def o_stuff():
    pass

def more_stuff():
    pass

IDEs with code-completion will typically also respect __all__ (though I'm unfamiliar with Visual Studio, so I don't know whether IntelliSense does so).

An alternative, included here for completeness although I would strongly recommend against it (on the grounds that it'll annoy anyone reading your code to distraction) is to import modules as an underscore-prefixed alias:

# ugly_as_sin.py

import os as _os

def o_stuff():
    return _os.name

Again, both from module import * and, typically, code-completion will ignore underscore-prefixed names.

Comments