代码之家  ›  专栏  ›  技术社区  ›  Campiotti

在Python中,将潜在的bool转换成bool,有什么缺点吗?

  •  0
  • Campiotti  · 技术社区  · 6 年前

    在我的python代码中,我将bool()的一些类型转换为变量,我知道这些变量可能已经是布尔型的了。这有什么坏处吗(性能等)

    下面是我正在使用的函数的基本克隆。

    import re
    pattern= "[A-Z]\w[\s]+:"
    other_cond= "needs_to_be_in_the_text"
    def my_func(to_check: str) -> bool:
        res = re.search(pattern, to_check)
        res2 = other_cond in to_check
        return bool(res), bool(res2) # res2 either None or True
    # I need boolean returns because later in my code I add all these  
    # returned values to a list and use min(my_list) on it. to see if
    # there's any false value in there. min() on list with None values causes exception
    
    3 回复  |  直到 6 年前
        1
  •  2
  •   Chris_Rands    6 年前

    bool() 没有必要,你可以用更惯用的 if: if not: 语法,但是如果有必要并且您希望避免 布尔() operator.truth here ).

    布尔() 速度相对较慢(但这通常是不必要的微观优化):

    In [1]: import operator
    
    In [2]: %timeit bool('')
    130 ns +- 0.528 ns per loop (mean +- std. dev. of 7 runs, 10000000 loops each)
    
    In [3]: %timeit operator.truth('')
    87.9 ns +- 0.0777 ns per loop (mean +- std. dev. of 7 runs, 10000000 loops each)
    
    In [4]: %timeit not not ''
    25.3 ns +- 0.176 ns per loop (mean +- std. dev. of 7 runs, 10000000 loops each)
    
        2
  •  1
  •   L3viathan gboffi    6 年前

    取决于“少数”是什么,但通常不是。

    当然打电话了 bool 比不打电话慢 布尔


    理论上,将变量 布尔 可以触发大对象的垃圾回收,例如:

    x = list(range(100000))
    x = bool(x)
    if x:
        foo()
    

    if body被调用:当强制转换时,原始列表超出范围并被垃圾收集,当不强制转换时,原始列表保留在内存中。

    我认为这些都是边缘案件。

        3
  •  1
  •   mfitzp    6 年前

    在没有看到示例代码的情况下进行注释是很困难的,但是 bool 可能会影响代码的可读性。例如,如果语句隐式地检查语句的真实性,那么 布尔 不会给你任何东西。

    a = [1,2,3]
    
    if a:
        pass
    

    而包装在布尔,这只是意味着更多的阅读。

    if bool(a):
        pass
    

    如果你分配给新的变量,这意味着需要跟踪更多的事情,并且可能会引入一些错误,在这些错误中,转换的变量和原来的变量不同步。

     a = [1,2,3]
     a_bool = bool(a)
    
     if a_bool:
          pass # will hit
    
     a = []
    
     if a_bool:
         pass # will still get here, even though you've updated a
    

    a = [1,2,3]
    if a:
       pass # will get here
    
    a = []
    
    if a:
        pass  # won't get here.
    

    真实性 在Python中,变量的定义是经常被利用的,这使得代码可读性更好。花点时间习惯这种方式可能比把东西包装起来要好 .