user3401853
user3401853

Reputation: 97

how to make a python function as built-in function or the alike?

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!

Upvotes: 1

Views: 140

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122152

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.

Upvotes: 4

Related Questions