Reputation: 58791
Is it possible to import
everything (*
) from an existing Python module except a number of explicitly specified methods?
(Background: Against recommended Python practice it is common in FEniCS to do from dolfin import *
. A few of the methods names contain the string "Test" though (e.g., TestFunction()
) and are mistaken for unit tests by nose.)
Upvotes: 18
Views: 17018
Reputation: 1609
@alexander-zhukov's solution will work most of the time, but not when the imported module coincidentally contains a variable called globals
.
For example,
to_exclude = ['abort']
from flask import *
for name in to_exclude:
del globals()[name]
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: 'module' object is not callable
The error is because the flask
package contains a namespace called globals
(that cannot be called) which will overwrite your current global symbol globals
.
The following solution will work for flask and others:
to_exclude = ['abort']
from flask import *
for name in to_exclude:
__builtins__.globals().pop(name)
However ridiculously, it does not work if you open a Python console and type in the commands manually. I think this is a defect of Python 3. If you want this to work in a Python console, then you have to explicitly import the builtins
module:
import builtins
to_exclude = ['abort']
from flask import *
for name in to_exclude:
builtins.globals().pop(name)
Upvotes: 2
Reputation: 4557
In case you don't have an access to the module, you can also simply remove these methods or variables from a global namespace. Here's how this could be done:
to_exclude = ['foo']
from somemodule import *
for name in to_exclude:
del globals()[name]
Upvotes: 22
Reputation: 99640
Yes, you can define the __all__
module
Add
__all__ = ["echo", "surround", "reverse"] #Or whatever your module names are
to the file which has these modules, or __init__.py
of the package you want to import from.
Now
from module import *
imports only the specified modules in __all__
Upvotes: 15