I want to test whether modules exists in python or not? but there seems no direct solution, so I wrote a function as below:
vim
I hope everytime I open the python interactive interface, I can simply type
test_module(module_name)
and thus check whether a module is existent or not.
so how can I make this function as something like built-in function so as to reach my target?
thanks!
1 Answer 1
You can add it to the __builtin__ module:
import __builtin__
def test_module(module_name):
# do something here
__builtin__.test_module = test_module
In Python 3, the module is called builtins instead.
If you want this to be run every time you open your Python interpreter, you can create a usercustomize.py module in USER_SITE location; it'll be imported everytime you run Python.
Be careful with expanding the built-ins, however. Adding names there makes them accessible globally by all Python code, and if any such code has accidentally or deliberately uses test_module where a NameError should have been raised, now uses your custom function.
It's much better to put such things into a dedicated module and only import this when you actually need that function. Explicit is better than implicit.
5 Comments
__builtin__ it may mask errors.foobar is set, catches the NameError and handles that by setting something. The code expects foobar not to exist. Then you add foobar to the Python built-ins, you now broke that module.
import myModule. If it saysImportError, then it doesn't exist. You can also see a list of all modules withhelp("modules")