Python modules: how to keep private table of private symbols?

I have a module in which I import other modules (usually sys

or os

), and when I import a module with

import mymodule

      

if i do something like this

dir(mymodule)

      

I get not only the submodules of the module, but os

et al.

['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'os', 'sys', 'submodule']

      

Is there a way to avoid importing modules inside my module into the module's symbol table? Can you keep it confidential?

+3


source to share


2 answers


There is no such thing as 'private' in Python; you use the leading underscore for names if you want to communicate that the name is private. Experienced Python developers will understand that these names should not be used outside of a module.

dir()

(really a debug tool) shows you the global namespace of your module, and you don't have to worry about how to import modules from that list; this is completely normal. Any code in this module (in function or generator expressions) that uses sys

either os

or submodule

as the global name resolves to a reference from that namespace. Thus, you want those names to be there for your code to keep running.

You can create a name sequence __all__

in your global namespace to display all the names you want other users to use from your module. dir()

I will not use it, but the syntax is like from mymodule import *

, and help(mymodule)

performs this sequence.

You can also provide those modules where you imported the 'private' names:



import os as _os
import sys as _sys

      

and update all links in your code to use these updated names. If you have not set __all__

then from mymodule import *

and help(mymodule)

will ignore names starting with underscores.

And you can always use del os

or del sys

if you only used those modules at the top level and no functions in your code require these names to exist as global.

+1


source


Well, you can remove a module from the namespace with del

:

import os

# ... all other code here

del os

      



After that, it will no longer be visible on import.

However, this will not work when modules are actually used ...

+2


source







All Articles