Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it valid to use conditional expressions for side effects?

I'm trying to figure out what the best way of doing this is:

resource['contents'][media_type] = []
resource['contents'][media_type].append(row[0].toPython()) if row[0] is not None else None
resource['contents'][media_type].append(row[2].toPython()) if row[2] is not None else None

I think the code is quite simple; if the rows have a value then add them to the list. Is this approach considered OK? Is there any other approach that would be better? The toPython method will return the string description of the contained object.

like image 326
Giannis Avatar asked Sep 08 '15 09:09

Giannis


People also ask

What is the use of conditional expression?

Conditional operators are used to evaluate a condition that's applied to one or two boolean expressions. The result of the evaluation is either true or false. There are three conditional operators: && the logical AND operator.

What is a conditional expression example?

if (y > z) x = y; else x = z; The following expression calls the function printf , which receives the value of the variable c , if c evaluates to a digit. Otherwise, printf receives the character constant 'x' .


3 Answers

Using a "ternary" conditional expression (x if C else y) for side effects is not at all Pythonic. Here's how I would do it:

resource['contents'][media_type] = []
for index in (0, 2):
    item = row[i]
    if item is not None:
        resource['contents'][media_type].append(item.toPython())

or using a list comprehension to reduce verbosity:

resource['contents'][media_type] = [row[i].toPython() for i in (0, 2) 
                                    if row[i] is not None]

These approaches are much more readable, and reduce duplication.

like image 106
jonrsharpe Avatar answered Nov 15 '22 21:11

jonrsharpe


I don't think it is considered good practice to do that. What you could do instead is:

resource['contents'][media_type] = []

for irow in [0, 2]:
    if row[irow] is not None:
        resource['contents'][media_type].append(row[irow].toPython())

This allows you the flexibility of also using ranges (for irow in range(5)), or using rows if you can access them directly (for row in rows:).

like image 35
Jean Nassar Avatar answered Nov 15 '22 21:11

Jean Nassar


No, that's not a valid use of a conditional expression. It confuses anyone trying to read your code.

Use an if statement; you can save some space by creating another reference to the list:

lst = resource['contents'][media_type] = []
if row[0] is not None: lst.append(row[0].toPython()) 
if row[2] is not None: lst.append(row[2].toPython())

but use a better name for the local reference (contents perhaps?), or use a list comprehension:

resource['contents'][media_type] = [
    col.toPython() for col in (row[0], row[2]) if col is not None]
like image 35
Martijn Pieters Avatar answered Nov 15 '22 19:11

Martijn Pieters