【问题标题】:Is there an analog to `return` when importing a module in python?在 python 中导入模块时是否有类似于“return”的方法?
【发布时间】:2016-03-20 03:18:37
【问题描述】:

免责声明

我知道,我可以简单地在if __name__ == '__main__ 下编写缩进的代码或将其放入函数中。但是,这会增加不必要的缩进级别。我也知道这会是不好的风格,我应该写一个合适的模块。我只是想知道。与setuptools 一起使用的入口点当然更好,人们不应该偷懒,将它们与 virtualenv 一起用于测试。我问这个问题是为了纯粹的学术知识'是否有一个命令可以提前完成导入文件'。


实际问题

可以提前返回函数以防止函数代码的其余部分执行。这有利于节省缩进级别。示例:

def my_func(arg):
    print arg
    if arg == 'barrier':
        return
    print 'arg is not barrier'
    # ...
    # alot more nested stuff that
    # will not be executed if arg='barrier'

保存缩进级别,与:

def my_func(arg):
    print arg
    if arg == 'barrier':
        return
    else:
        print 'arg is not barrier'
        # ...
        # alot more nested stuff that
        # is one indentation level deeper :-(

是否可以在导入模块时做类似的事情,从而不导入其余代码? 例如在模块文件中:

# !/usr/bin/python
# I'm a module and a script. My name is 'my_module.py'.
# I define a few functions for general use, and can be run standalone.

def my_func1(arg):
    # ... some code stuff ...
    pass

def my_func2(gra):
    # ... some other useful stuff ...
    pass

if __name__ != '__main__':
    importreturn   # Statement I'm looking for that stops importing
    # `exit(0)` here would exit the interpreter.

print 'I am only printed when running standalone, not when I'm imported!'
# ... stuff only run when this file is executed by itself ...

所以我看不到 “我只在独立运行时打印,而不是在导入时打印!”,当我这样做时:

import my_module.py
my_func2('foobar')

【问题讨论】:

  • 但是,这会增加一个不必要的缩进级别 - 如果需要添加一个缩进级别,它在什么方面是“不必要的”?
  • 从某种意义上说,有了函数,你可以通过返回函数来摆脱它。我只是想知道是否有一种“返回”的方式,过早地阅读“终止”文件的导入。诚然,我的示例不是一个很好的用例,但可能还有其他用例。将其视为“假设”类型的问题。
  • 将可选代码放到另一个模块中,从 x import * it.
  • @RemcoGerlich:我喜欢这样,它结合了可读性和正确性。我仍然会对这个问题感兴趣,如果 python 中有一条语句中途停止导入模块。
  • 答案是“不”,我很确定。

标签: python return python-import


【解决方案1】:

您不想避免缩进,缩进简明扼要地说明了您打算代码做什么:

if __name__ == '__main__':
    print "I am only printed when running standalone, not when I'm imported!"
else:
    print "I am only printed when importing"

如果你愿意,你可以把它包装在一个函数中?

def main():
    if __name__ == '__main__':
        print "I am only printed when running standalone, not when I'm imported!"
        return
    print "I am only printed when importing"

main()

【讨论】:

  • 您好,感谢您的关注。我知道我可以这样做,并且通常出于样式原因我希望有缩进。除了这次我没有。我想我在我的问题中提到了这一点。该函数也将具有“额外”缩进。
【解决方案2】:

不,Python 中没有这样的声明。

与您想要的最接近的是引发异常并在 try/except 块中进行导入。 raise 语句后面的代码不会被执行。

要真正实现这样的语句,您需要一个自定义导入处理程序来进行一些预处理,和/或自定义编译器。如果您想了解 Python 内部结构,这可能是一个有趣的挑战,但不应该在实际应用程序中使用。

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 2020-12-25
    • 2015-11-22
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    相关资源
    最近更新 更多