chmod 777 j
chmod 777 j

Reputation: 557

Most pythonic way to convert to boolean?

What is the most pythonic way to convert to boolean based on the truthiness of the object?

return bool(an_object)

or

if an_object:
    return True
else:
    return False

or something else entirely?

In this instance we can't get by relying on the truthiness of the object.

Upvotes: 4

Views: 782

Answers (2)

Gadi
Gadi

Reputation: 1152

Depending what you need, you can

 return not an_Object is None

or whatever your predicate is. This will allow you to control which objects are True and which are None

Upvotes: 0

mgilson
mgilson

Reputation: 309889

If you really need a boolean, use bool(something)...

However, usually you don't need a boolean so rather than return bool(something), you can just return something and the user can then decide what context to use it in.

Upvotes: 10

Related Questions