Inline if statements

In some cases, you just want to assign (or reassign) variables. Bad practice would involve doing the following:

name = name or 'Sigizmund'

Here, name will have a value of Sigizmund if it was equal to Sigizmund before, or is untruthy (equal to None, False, or zero). This is fine in certain cases, but can lead to uncertainty due to ambiguity. A better solution would be to use if instead:

name = name if name is not None else 'Sigizmund'

Here, the logic is exactly the same—name will have a value Sigizmund if not None, but stated more explicitly. One key difference is that the preceding statement will not consider untruthy values as None—if name is equal to False or zero, it will not be overwritten. Perhaps counterintuitively, this is considered a better practice—if the value is somehow invalid, it is better to know this as soon as possible.

Another option is to use if as part of the comprehension—we actually did just that in the previous chapter. Let's revisit that example in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset