Home > Back-end >  Python - How to properly access class members if the instance itself is not None
Python - How to properly access class members if the instance itself is not None

Time:11-08

Coming from c this implementation looks similar to accessing pointers, in python is there more elegant way to do this?

        if something is not None:
            return something.x
        else:
            return None

if the instance itself is not null, then allow accessing its members.

any ideas? thanks

CodePudding user response:

For best clarity and easier for newcomers to understand, I believe you can use a single line if-else statment in Python:

val = something.x if something else None

As mentioned in comments, the above will go the else part even if something is a falsy value, such as 0.

In that case, you could also add an explicit check for a None value:

val = None if something is None else something.x

CodePudding user response:

If something is known to be either None or truthy (for example user-defined types that don't specify a __bool__ method), you can use something and something.x

There is PEP 505 which has been deferred, but if accepted (which is unlikely) would allow something?.x to get your specific behaviour.

  • Related