【问题标题】:python if/else and try/except combination without redundancypython if/else 和 try/except 组合没有冗余
【发布时间】:2021-04-06 12:53:40
【问题描述】:

在玩icecream 时,我编写了以下代码行

if __debug__:
    try:
        from icecream import ic
        ic.configureOutput(includeContext=True)
    except ImportError:  # Graceful fallback if IceCream isn't installed.
        ic = lambda *a: None if not a else (a[0] if len(a) == 1 else a)  # noqa
else:
    ic = lambda *a: None if not a else (a[0] if len(a) == 1 else a)  # noqa

如您所见,我想在这两种情况下都将(相同的)lambda 表达式分配给 ic

  1. 如果不调试代码或
  2. 如果导入冰淇淋不起作用

我想知道是否有一种(可能是 pythonic 的)方法来处理这个想法而没有冗余。

【问题讨论】:

  • ic = lambda ... if not __debug__: try: import ... except ImportError: pass...?
  • 感谢@deceze,这个“覆盖”ic-definition 是个好主意,但不是那种 Python 风格,不是吗?
  • 为什么不呢?
  • @deceze 我认为重新定义/覆盖在某种程度上是不干净的。但这只是个人感觉。确实,您的建议满足了我的要求,因此很好。如果没有进一步的解决方案出现,我当然会接受它作为你的答案(如果你喜欢这样写的话)。或者我会通过自我回答提及你。
  • @deceze 我根据您的评论添加了an answer,谢谢! LMK 如果您有任何想要添加的内容。

标签: python python-3.x if-statement try-except


【解决方案1】:

您可以定义一个默认值,然后根据需要覆盖它。我还会添加 cmets 以使其清楚。

def ic(*a):  # May be overridden later
    if not a:
        return None
    return a[0] if len(a) == 1 else a


if __debug__:
    try:
        from icecream import ic  # Override default
    except ImportError:
        pass  # Fallback to default
    else:
        ic.configureOutput(includeContext=True)

顺便说一句:

这是基于decezecomment

【讨论】:

  • 我会直接在导入旁边添加一个内联注释,以便 200% 清楚地表明覆盖是有意的。随着时间的推移/重构此连接可能会丢失。
  • 我推荐 `#noqa: F811 - no redefinition-error` 在 icecream-import-line 中,因为这是相应的警告 (c. f. flake8) @ojdo
  • 通过所有重构,这可能是 codereview.SX 的候选者:D
【解决方案2】:

与 cmets 中 deceze 建议的模式略有不同:

# file my_icecream.py:
def ic(*a):
    """Icecream fallback implementation"""
    if not a:
        return None
    elif len(a) == 1:
        return a[0]
    else:
        return a
# original file
if not __debug__:
    from my_icecream import ic
else:
    try:
        from icecream import ic
        ic.configureOutput(includeContext=True)
    except ImportError:
        from my_icecream import ic

【讨论】:

  • 谢谢,看起来很有趣。只是一个问题:为什么要反转 if 子句?有没有更大的意义?更进一步 - 在my_icecream.py 中,你为什么要扩展单线?
  • 两者都是纯粹的风格选择:“oneliner”的分解对我来说看起来更具可读性,每当以后需要掌握/修改/适应它时;但在大多数情况下,它的实现可能/应该像 icecream 导入一样不透明。
  • 至于反转 not __debug__:我发现先使用默认/生产案例更简洁,但我很容易被说服遵守您发布的顺序。
猜你喜欢
  • 2021-03-15
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 2011-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多