首页 > 解决方案 > 使功能无需全局导入即可使用

问题描述

假设我想为一个项目制作一个核心库,其功能如下:

def foo(x):
    """common, useful function"""

我想让这些函数在我的项目中全局可用,这样当我在文件中调用它们时,我不需要导入它们。我有一个 virtualenv,所以我觉得我应该能够修改我的解释器以使它们在全球范围内可用,但不确定这背后是否有任何既定的方法。我知道它违反了一些pythonic原则。

标签: pythonimportglobal-variables

解决方案


可以创建一个自定义“启动器”来设置一些全局变量并在 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 *是一种更好的方法。

前两个变体的缺点是没有工具会知道您注入的全局变量的任何信息。例如mypyflake8我知道的所有 IDE 都会失败。


推荐阅读