Home > Mobile >  Is there an alternative to "not not" when declaring a predicate to indicate value of strin
Is there an alternative to "not not" when declaring a predicate to indicate value of strin

Time:06-10

Assuming I have some_str_value and I would like to have a predicate variable to indicate whether or not this value is "Truthy" (has a value).

The verbose way would be:

predicate = some_str_value is not None and len(some_str_value) > 0

one could also write:

predicate = not not some_str_value

  1. Is there a shorter way than this awkwardly unzenful syntax?
  2. If not, is there a common straightforward alternative?

CodePudding user response:

I think you just want bool, i.e. whether or not a value is "truthy"

>>> bool("hi")
True
>>> bool("")
False
>>> bool(None)
False

Note, to be pedantic, this doesn't really mean the same thing as "has a value". If a variable is defined in Python, then it has some value. For most built-in containers, and I suppose stings, the idea is that it is "non-empty".

I will also note that having this predicate variable is almost always redundant. Because basically every place you would use predicate, e.g.:

if predicate:
    do_something()

You could always just replace it with:

if some_str_value:
    do_something()

So, I would just caution that this might not be needed at all.

Of course, in some cases, you do want a bool object, e.g. counting the number of non-empty strings in a list:

>>> sum(map(bool, ["foo", "", "bar", ""]))
2
  • Related