【问题标题】:How to simplify 2 conditions that rely on one another but lead to the same result?如何简化两个相互依赖但导致相同结果的条件?
【发布时间】:2017-08-04 20:58:51
【问题描述】:

我有一个接受整数年份的函数,但我也希望用户能够传入字符串 'ALL' 并且仍然能够取回一些东西。

我现在有这段丑陋的代码:

if type(year) != str or (type(year) == str and year.upper() != 'ALL'):
    total_results = self.filterResultsByYear(total_results, year, year2)

结果默认过滤到当前年份,可以按其他年份过滤,但如果用户不想过滤,则必须传入“所有”年份。

我写上述可憎的原因是如果我只有if year.upper() != 'ALL',如果我传入一个整数,我会得到一个TypeError。如果我输入if type(year) != str and year.upper() != 'ALL',我仍然会得到同样的错误。上面的代码看起来真的很难看,我想让它更 Pythonic。我需要什么工具来做到这一点?

【问题讨论】:

  • year 是字符串但不是“全部”时,预期的行为是什么?
  • 您是否总是希望输入有效?如果不是,我会说只是检查它是否是有效的年份,或者根本不应用过滤器。
  • @DYZ 我想抛出错误/警告用户输入无效。基本上我希望默认情况下应用过滤器,如果用户提供了一个 int,但如果用户提供了一个字符串并且该字符串恰好是'all',那么我想忽略过滤器。

标签: python conditional-statements idioms simplification


【解决方案1】:

取决于 total_resultsyear2 是什么以及您希望如何处理它们:

try:
    year = int(year)
    total_results = self.filterResultsByYear(total_results, year, year2)
except ValueError:
    if not isinstance(year, (str, unicode)):
        raise  # Not string, unicode or coercible to an integer.
    if year.lower() == 'all':
        # Your logic here.
    else:
        # String but not 'all'.  Exception handling.

顺便说一句,要检查类等价,请使用 isinstance(object, class)isinstance(object, (class 1, class 2, ...))

【讨论】:

  • 我希望代码流工作的方式是应用过滤器,除非年份等于'all',否则它将被忽略。默认情况下应用过滤器。
猜你喜欢
  • 1970-01-01
  • 2011-04-26
  • 1970-01-01
  • 1970-01-01
  • 2021-09-19
  • 2013-03-18
  • 1970-01-01
  • 1970-01-01
  • 2020-09-25
相关资源
最近更新 更多