1

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
  • I have an alternative proposal for checking whether a module exists. Type import myModule. If it says ImportError, then it doesn't exist. You can also see a list of all modules with help("modules") Commented Apr 7, 2014 at 16:57

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

5 Comments

you meant if I use builtin module, the function can't be imported everytime I run python? then what is the usage of builtin module?
No, I mean that if you add the function to __builtin__ it may mask errors.
I don't understand. what is the relation between my question and "builtin may mask errors"?
@user3401853: Say you are running code that explicitly tests if 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.
@user3401853: Adding a new name as a built-in affects all Python code, and you cannot always predict how that code is going to handle the new name in the namespace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.