停止模块内的评估

10 投票
6 回答
2925 浏览
提问于 2025-04-16 00:43

我已经习惯写这样的函数:

def f():
  if sunny:
    return
  #do non-sunny stuff

我正在尝试找出在模块中使用的等效语法。我想做类似这样的事情:

if sunny:
  import tshirt
  #do something here to skip the rest of the file
import raincoat
import umbrella
#continue defining the module for non-sunny conditions

我知道我可以用if/else来写,但把整个模块的其余部分都缩进看起来有点傻。

我可以把其余的代码移到一个单独的模块里,然后根据条件导入,但这样做似乎很麻烦。

6 个回答

0

我真的推荐这个解决方案:

if sunny:
    print "it's sunny"
else:
    exec '''
print "one"
print "two"
x = 3
print x
# ETC
'''

其实不是。但确实有效。

1

我也遇到了类似的情况,不想在我的模块里缩进一大堆代码。我使用了异常来停止加载模块,然后捕获并忽略这个自定义的异常。这样做让我的Python模块变得很程序化(我想这可能不是最理想的),但这帮我省去了很多代码修改。

我有一个公共/支持模块,在里面定义了以下内容:

import importlib

def loadModule(module):
    try:
        importlib.import_module(module)
    except AbortModuleLoadException:
        pass;

class AbortModuleLoadException(Exception):
    pass;

这样,如果我想“取消”或“停止”加载一个模块,我可以这样加载这个模块:

loadModule('my_module');

在我的模块内部,我可以针对某个条件抛出以下异常:

if <condition>:
    raise AbortModuleLoadException;
2

把文件分开和额外的缩进可能是合理的,因为这本身就是一件比较奇怪的事情。

根据你实际需要的内容,你可以先处理整个模块的内容,然后再在后面删除那些不合适的部分。

def foo(): 
  print "foo"
def bar(): 
  print "bar"

if sunny:
  del foo
else:
  del bar

撰写回答