Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there an alternative to "not not" when declaring a predicate to indicate value of strings in python?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading