Home > Net >  How to declare if 'string' in statement if variable could be none
How to declare if 'string' in statement if variable could be none

Time:04-13

I have a variable that usually gets string values and sometimes it could be NoneType. If have to apply an OR condition to it and it is important to verify if a string is contained on it.

The current code that is giving me a 'TypeError: argument of type 'NoneType' is not iterable' is the following:

if 'string' in my_var or not my_var:
    do_something()

Naturally, I solved this issue for my current input by forcing my_var to be a string in the if condition, but I don't think it is a pythonic way to solve it and i think it could throw me some errors for more complex inputs:

 if 'string' in str(my_var) or not my_var:
        do_something()

So, I would like to have a more "correct" solution for the issue I'm facing

CodePudding user response:

Oh dear, this is just like possibly having null pointers in C/C . You have to check whether my_var is not None before assuming its a str:

if my_var is not None or 'string' in my_var:
    do_something()

(In my comment I had: if not my_var which might not be what you want since this bit is True if my_var is the empty string)

CodePudding user response:

You should use isinstance(my_var, str) to check if my_var is a string.

if my_var is not None and isinstance(my_var, str):
  • Related