python - 导入时是否有退出模块的命令,例如返回函数

标签 python python-import

当您在 Python 中导入模块时,模块代码是“运行”的。有时在模块中有分支逻辑很有用,例如检查包版本或平台或其他。有没有办法在到达文件末尾之前退出整个模块执行,相当于函数中的提前返回?

如果模块作为脚本运行,您可以 exit() 但这会主动引发异常并终止整个过程。我只想说,到此为止,不要再在下面运行任何代码。

基本上我可以改造这个

if not <condition>:
    MY_CONSTANT = 3.14
    class blah():
       ...

    def foo(x):
       ...

    # rest of module....

进入

if <condition>:
    return from module

MY_CONSTANT = 3.14
class blah():
   ...

def foo(x):
   ...

# rest of module....

主要是为了让我不必编写很多看起来很奇怪的额外缩进级别的代码。

最佳答案

您可以创建自定义 Loader那些特殊情况,例如ImportError (1) 作为停止 module execution 的快捷方式.这可以通过自定义注册 Findersys.meta_path .

所以如果你有以下模块要导入:

# foo.py

x = 1
raise ImportError  # stop module execution here
y = 2

您可以使用以下查找器/加载器导入该模块。它将一直执行到遇到 raise ImportError 为止。

import importlib


class Loader(importlib.machinery.SourceFileLoader):
    def exec_module(self, module):
        try:
            super().exec_module(module)
        except ImportError:  # the module chose to stop executing
            pass


class Finder(importlib.machinery.PathFinder):
    @classmethod
    def find_spec(cls, fullname, path=None, target=None):
        spec = super().find_spec(fullname, path, target)
        if spec is not None:
            spec.loader = Loader(spec.name, spec.origin)  # register the custom loader
        return spec


import sys

sys.meta_path.insert(2, Finder())  # from now on the custom finder will be queried for imports


import foo

print(foo.x)  # prints 1
print(foo.y)  # raises AttributeError

(1) 使用ImportError 来指示快捷方式显然有其缺点,例如如果您的模块试图导入其他不存在的东西,这不会被报告为错误但是该模块只是停止执行。所以最好改用一些自定义异常。我只是为了示例而使用 ImportError

关于python - 导入时是否有退出模块的命令,例如返回函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64061426/

相关文章:

python - 如何在python中合并多个coco json文件

python - 在 python 文件夹中导入图表/结构(清理代码)

python - 全部导入 不全部导入

python - 确保 Python 中不存在 __init__ 函数

python - 我的 Mercurial Hook 是否可以从另一个文件调用代码?

python - 在机器人中的测试用例之间切换时,我的实例变量(自身)没有被保存,是否有原因?

Python Tkinter 如何使文本框滚动

Python TypeError - 预期字节但在尝试创建签名时得到 'str'

python - 强制 python 使用旧版本的模块(比我现在安装的)

python - 增加 Kubernetes 部署中 Dask Worker 的数量