Home  >  Article  >  Backend Development  >  How to make a custom function in Python available globally?

How to make a custom function in Python available globally?

WBOY
WBOYforward
2023-05-08 09:43:071351browse

When we develop Python projects, we often write some tool functions. In order to use this tool function in multiple .py files in the project, you have to import it in multiple places, which is very troublesome.

For example, the following example:

How to make a custom function in Python available globally?

Both the A.py and C.py files must use the clean_msg​ tool function, then they must Import clean_msg from util.py​. This seems natural.

But today when I was looking at the source code of icecream/builtins.py[1], I suddenly discovered an advanced usage that allows us to use tool functions just like using Python’s print function. No need to Import, use it directly instead.

Let’s take a look at the effect first:

How to make a custom function in Python available globally?

Everyone pay attention to A.py and C.py​, I did not import clean_msg but used this directly function. And it runs completely fine.

The key principle is in the entry file main.py, the 3 lines I framed:

import builtins

from util import clean_msg
setattr(builtins, 'clean_msg', clean_msg)

In Python, all built-in functions or classes are in the builtins module, so in It can be used directly in the code without importing. Now we only need to register our custom tool function into the builtins module, so that it can have the same effect as the built-in function.

If you want to register a tool function as a built-in function, you only need to import it in the entry file, and then use setattr to set it as an attribute of the builtins module. The second parameter is the name when you want to call it globally, and the third parameter is the tool function you need to register. The name can be different from the name of the utility function, as long as it does not duplicate an existing built-in function.

After the registration is completed, during the entire runtime of this project, this tool function can be called directly through the registered name in any .py file, just like calling the built-in function.

Reference materials

[1] icecream/builtins.py: https://github.com/gruns/icecream/blob/master/icecream/builtins.py​

The above is the detailed content of How to make a custom function in Python available globally?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete