Pythonic获取对象布尔值的方法

gri*_*ton 0 python

我希望能够以最惯用的方式编写一个函数,True如果一个对象是真实的,False则返回该函数.例如:

is_truthy(True) # True
is_truthy(False) # False
is_truthy(123) # True
is_truthy(0) # False
is_truthy("some string") # True
is_truthy("") # False
Run Code Online (Sandbox Code Playgroud)

我想出的最好的是:

def is_truthy(obj):
    return not not obj
Run Code Online (Sandbox Code Playgroud)

谁能做得更好?

小智 8

is_truthy = bool
Run Code Online (Sandbox Code Playgroud)

内置设备让你满意.


dok*_*ebi 5

你可以这样做:

bool(obj)
Run Code Online (Sandbox Code Playgroud)