Boldewyn Boldewyn -4 years ago 155
Python Question

Prevent Python packages from re-exporting imported names

In a Python package, I have the file structure

package/
__init__.py
import_me.py


The file
import_me.py
is thought to provide snippets of functionality:

import re
import sys

def hello():
pass


so that
package.import_me.hello
can be imported dynamically via
imp
. Unfortunately, this also allows to import
re
and
sys
as
package.import_me.re
and
package.import.sys
, respectively.

Is there a way to prevent the imported modules in
import_me.py
to be re-exported again? Preferably this should go beyond name mangling or underscore-prefixing imported modules, since in my case it might pose a security problem under certain instances.

Answer Source

There is no easy way to forbid importing a global name from a module; Python simply is not built that way.

While you could possibly achieve the forbidding goal if you wrote your own __import__ function and shadowed the built-in one, but I doubt the cost in time and testing would be worth it nor completely effective.

What you can do is import the dependent modules with a leading underscore, which is a standard Python idiom for communicating "implementation detail, use at your own risk":

import re as _re
import sys as _sys

def hello():
    pass

Note

While just deleting deleting the imported modules as a way of not allowing them to be imported seems like it might work, it actually does not:

import re
import sys

def hello():
    sys
    print('hello')

del re
del sys

and then importing and using hello:

>>> import del_mod
>>> del_mod.hello()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "del_mod.py", line 5, in hello
    sys
NameError: global name 'sys' is not defined
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download