Question

I'm building a json and I want to split a comma seperated list ID's in array of ID's and put in the json. The problem is that the list can also be NULL in the database, thus None in python

part of the code looks like:

'followupsteps': [{
    'id': stepid,
} for stepid in string.split(step.followupsteps, ',') 

I tried things like:

'followupsteps': [{
    'id': stepid,
} for stepid in (string.split(step.followupsteps, ',') if not None else [])]

and

'followupsteps': [{
    'id': stepid,
} for stepid in string.split((step.followupsteps if not None else ''), ',')]

they all result in the Django/python error: Exception Value: 'NoneType' object has no attribute 'split'

any ideas?

Was it helpful?

Solution

You want to test if step.followupsteps is boolean true instead:

'followupsteps': [] if not step.followupsteps else [{
    'id': stepid,
} for stepid in step.followupsteps.split(',')]

You are instead testing if not None is True, which it just so happens to be:

>>> bool(not None)
True

not step.followupsteps is going to be True if it is an empty string, None, numeric 0 or an empty container. You could also use if step.followupsteps is None but why limit yourself.

Another way of spelling this:

'followupsteps': [{
    'id': stepid,
} for stepid in (step.followupsteps.split(',') if step.followupsteps else [])]

but by just returning an empty list first you avoid the empty list comprehension altogether.

OTHER TIPS

Your ternary statement expands to:

if not None:
   step.followupsteps
else:
   ''

not None always evaluates to True, so this is equivalent to not writing an if/else statement at all.

You want to be writing (thing to evaluate) if step.followupsteps else (default thing), taking advantage of the 'falsiness' of an object that is None. Or, if it's more convenient, (default thing) if not step.followupsteps else (thing to evaluate).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top