5

As you know over Python 3.6, there is a feature known as format string literals. str(obj['my_str_index']) can be either None or a string value. I've tried the below one but it doesn't yield 'null' text if it is None.

foo = "soner test " \
f"{str(obj['my_str_index']) if str(obj['my_str_index']) is not None else 'null'}

2 Answers2

4

str(None) is not None, but "None". So without that useless and harmful stringification:

foo = "soner test " \
f"{str(obj['my_str_index']) if obj['my_str_index'] is not None else 'null'}"

EDIT: A more legible way (note that interpolation in an f-string automatically stringifies, so we don't need str at all):

index = obj['my_str_index']
if index is None:
    index = "none"
foo = f"soner test {index}"

EDIT: Another way, with the walrus (limited to 3.8+):

foo = f"soner test {'null' if (index := obj['my_str_index']) is None else index}"
Amadan
  • 191,408
  • 23
  • 240
  • 301
3

You can greatly simplify the condition. This will work (in most cases, see the caveat below) and in my opinion a bit more readable

foo = f"soner test {obj['my_str_index'] or 'null'}"

You don't have to worry about str(...) because the interpolation mechanism calls the objects __str__ method implicitly (if it does not have __format__).

The only caveat with this approach is that foo will contain null if obj['my_str_index'] is any of the falsey values (None, 0 and any empty sequence).

DeepSpace
  • 78,697
  • 11
  • 109
  • 154