Is it bad practice to use the following format when my_var can be None?
if my_var and 'something' in my_var: #do something
The issue is that 'something' in my_var will throw a TypeError if my_var is None.
Or should I use:
if my_var: if 'something' in my_var: #do something
or
try: if 'something' in my_var: #do something except TypeError: pass
To rephrase the question, which of the above is the best practice in Python (if any)?
Alternatives are welcome!
It’s safe to depend on the order of conditionals (Python reference here), specifically because of the problem you point out – it’s very useful to be able to short-circuit evaluation that could cause problems in a string of conditionals.
This sort of code pops up in most languages: