1

I have found a weird function invocation while reading models.py file in python requests library. I tried to find some explanations in python official documentation but without any successes, unfortunately. Do you possibly know why such a case is possible or how to use logical operators in functions invocation? Are those a part of good practices? Please, find the code below.

fields = to_key_val_list(data or {})
files = to_key_val_list(files or {})
Denuil
  • 35
  • 1
  • 4

1 Answers1

1

This kind of things are used very often in python programming language

fields = to_key_val_list(data or {}) # this means, that if boolean value of data variable is False, use empty dict/or anything you want.

Also,,,

class Foo:

    def __init__(self, data: list):
        self.data = data or 'abc' # if data will be empty list self.data will become 'abc'

You can use and also. and/or both are available.

val = a or b or c # in the chain, if a is False, value of val would become b. if be is False also, then c
val = a and b and c # "and" checks values of whole chain. if a is False, so val will have same value as a. if all is true in chain, the last element value will be inside val.
gachdavit
  • 1,223
  • 1
  • 6
  • 7