← Back to Gists

Check NoneType before access

📝 Python
jeffrey_hendrix
jeffrey_hendrix · 4d ago
This 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

1
oneillh oneillh 2d ago
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.