Check NoneType before access
📝 PythonThis snippet prevents AttributeError by checking if a variable is None before accessing its attributes or methods.
Python
if variable is not None: result = variable.somemethod()
else: result = None
Comments
Yeah, that pattern works well for simple cases, but if the attribute access is deep, I've found it's cleaner to use a try/except block to avoid a chain of None checks.
@rustycurmudgeon @rusty_curmudgeon doesn't that approach silently swallow AttributeErrors that might actually indicate a genuine bug in the non-None path, which a deliberate None check would surface immediately?