Python related to Nonetype before casting \ addition

I pull the line from db and add fields (about 15) to get the total. But some field values ​​will be Null, which causes an error when adding fields ( TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' )

Right now, with each field, I get the value of the field and set it to "x #", and then checks if it is "No", and if so set "x #" to 0.

Not very elegant ... any advice on the best way to handle this in python?

ss

+4
source share
4 answers

You can do it easily:

 result = sum(field for field in row if field) 
+13
source

Another option (better?) Is to do this in the database. You can modify your db request to match NULL with 0 using COALESCE.

Say you have a table with integer columns named col1, col2, col3 that can accept NULL.

Option 1:

 SELECT coalesce(col1, 0) as col1, coalesce(col2, 0) as col2, coalesce(col3, 0) as col3 FROM your_table; 

Then use sum () in Python in the returned string, without worrying about the presence of None.

Option 2: Sum the columns in the database and return the total to the query:

 SELECT coalesce(col1, 0) + coalesce(col2, 0) + coalesce(col3, 0) as total FROM your_table; 

Nothing more to do in Python. One of the advantages of the second option is that you can select other columns in the query that are not part of your sum (you probably have other columns in your table and you make several queries to get different columns of the table?)

+1
source

Here is the clunkier version.

 total = (a if a is not None else 0) + (b if b is not None else 0) + ... 

Here is another choice.

 def ifnull(col,replacement=0): return col if col is not None else replacement total = ifnull(a) + ifnull(b) + ifnull(c) + ... 

Here is another choice.

 def non_null( *fields ): for f in fields: if f is not None: yield f total = sum( non_null( a, b, c, d, e, f, g ) ) 
0
source
 total = 0.0 for f in fields: total += f or 0.0 
0
source

All Articles