'Bypassing NoneType in a list comprehension

To work around when there is no value x.competition.name, I tried to use is not None:

'competition': [x.competition.name if x.competition.name is not None else '-' for x in a]

But the error still keeps showing up:

AttributeError: 'NoneType' object has no attribute 'name'

How can I go about getting around this problem?



Solution 1:[1]

Apparently competition is None, so please replace

[x.competition.name if x.competition.name is not None else '-' for x in a]

using

[x.competition.name if x.competition is not None else '-' for x in a]

Solution 2:[2]

The error message is saying that you tried to get None.name. That means x.competition must be None, which is why you can't get a name attribute from it. Instead, try making your condition x.competition is not None.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daweo
Solution 2 luther