Alex Blundell
Alex Blundell

Reputation: 2104

Python check for NoneType not working

I'm trying to check whether an object has a None type before checking it's length. For this, I've done an if statement with an or operator:

if (cts is None) | (len(cts) == 0):
return

As far as I can tell, the object cts will be checked if it's None, and if it is, the length check won't run. However, the following error happens if cts is None:

TypeError: object of type 'NoneType' has no len()

Does python check both expressions in an if statement, even if the first is true?

Upvotes: 8

Views: 42856

Answers (2)

Arovit
Arovit

Reputation: 3719

You can also use -

if not cts: return

Upvotes: 18

user2555451
user2555451

Reputation:

In Python, | is a bitwise or. You want to use a logical or here:

if (cts is None) or (len(cts) == 0):
    return

Upvotes: 27

Related Questions