Correct way to guard against 'NoneType' object has no attribute?


I’m still learning Python, so hoping someone can help me out here. In Javascript, you can easily guard against missing attributes by returning and empty list like:

constraints = context.scene.rigidbody_world.constraints.objects || []


context?.scene?.rigidbody etc…

What is the ‘correct’ way to deal with this issue in python, especially when the attribute is buried deep like objects in the above example. I’ve been resorting to nested ‘if hasattr(…’ statements, but googling about hasn’t really revealed the ‘right way’ to handle this.

Any help is appreciated! Thanks

There’s a lot o ways to handle it i usually do it with try/except or if != None

ah ok, i think using try/except method will be a neater way then my current ugly: -

if(context.scene.rigidbody_world is not None and

    context.scene.rigidbody_world.constraints is not None and

        context.scene.rigidbody_world.constraints.objects is not None):


yeah, one thing that is important to understand about Python that is different in every other language is that try/except is encouraged, just don’t try to catch general exceptions, try to be as specific as possible.

another thing to point out is that you can check if an object has an attribute using hasattr()

Thanks for the pointers! I had already discovered the hasatrr method, but generally with try/catch I wouldn’t have thought to use it for that purpose. But it’s a nice way to deal with the more specific issues I’ve encountered. :+1:t3: