python - 使功能无需全局导入即可使用
问题描述
假设我想为一个项目制作一个核心库,其功能如下:
def foo(x):
"""common, useful function"""
我想让这些函数在我的项目中全局可用,这样当我在文件中调用它们时,我不需要导入它们。我有一个 virtualenv,所以我觉得我应该能够修改我的解释器以使它们在全球范围内可用,但不确定这背后是否有任何既定的方法。我知道它违反了一些pythonic原则。
解决方案
可以创建一个自定义“启动器”来设置一些全局变量并在 python 文件中执行代码:
from sys import argv
# we read the code of the file passed as the first CLI argument
with open(argv[1]) as fin:
code = fin.read()
# just an example: this will be available in the executed python file
def my_function():
return "World"
global_variables = {
'MY_CONSTANT': "Hello", # prepare a global variable
'my_function': my_function # prepare a global function
}
exec(code, global_variables) # run the file with new global variables
像这样使用它:python launcher.py my_dsl_file.py
.
示例my_dsl_file.py
:
# notice: no imports at all
print(MY_CONSTANT)
print(my_function())
有趣的是,Python(至少是 CPython)使用不同的方式来设置一些有用的函数,比如help
. 它运行一个名为的文件,该文件site.py
将一些值添加到builtins
模块中。
import builtins
def my_function():
return "World"
builtins.MY_CONSTANT = "Hello"
builtins.my_function = my_function
# run your file like above or simply import it
import <your file>
我不会推荐这两种方式。简单from <your library> import *
是一种更好的方法。
前两个变体的缺点是没有工具会知道您注入的全局变量的任何信息。例如mypy
,flake8
我知道的所有 IDE 都会失败。
推荐阅读
- react-native - 子组件不与父组件一起呈现
- discord.py - 使用嵌入回复消息 (Discord.py)
- node.js - 使用 Twilio 拨打电话时,有没有办法将所有声音静音?
- blockchain - 如何下载区块链交易数据?
- python - 通过 OpenCV 中的视频从 ESP32 获取数据 - Python => 冻结视频
- pine-script - 尝试在 Tradingview 下画线时无法使用参数调用“绘图”
- python - 您如何找到设备连接到的串行端口?
- javascript - 如何使用 onClick 函数将 1 添加到查询字符串中的日期?
- javascript - 跳过空格的 JavaScript 习惯用法是什么?
- javascript - Axios 拦截器标头