If it's a dictionary you can use get(keyname, value)

{'foo': {'bar': 'baz'}}.get('foo', {}).get('bar')
Answer from Aliaksandr Sushkevich on Stack Overflow
🌐
Reddit
reddit.com › r/python › optional chaining operator in python
r/Python on Reddit: Optional chaining operator in Python
August 5, 2025 -

I'm trying to implement the optional chaining operator (?.) from JS in Python. The idea of this implementation is to create an Optional class that wraps a type T and allows getting attributes. When getting an attribute from the wrapped object, the type of result should be the type of the attribute or None. For example:

## 1. None
my_obj = Optional(None)
result = (
    my_obj # Optional[None]
    .attr1 # Optional[None]
    .attr2 # Optional[None]
    .attr3 # Optional[None] 
    .value # None
) # None

## 2. Nested Objects

@dataclass
class A:
    attr3: int

@dataclass
class B:
    attr2: A

@dataclass
class C:
    attr1: B

my_obj = Optional(C(B(A(1))))
result = (
    my_obj # # Optional[C]
    .attr1 # Optional[B | None]
    .attr2 # Optional[A | None]
    .attr3 # Optional[int | None]
    .value # int | None
) # 5

## 3. Nested with None values
@dataclass
class X:
    attr1: int

@dataclass
class Y:
    attr2: X | None

@dataclass
class Z:
    attr1: Y

my_obj = Optional(Z(Y(None)))
result = (
    my_obj # Optional[Z]
    .attr1 # Optional[Y | None]
    .attr2 # Optional[X | None]
    .attr3 # Optional[None]
    .value # None
) # None

My first implementation is:

from dataclasses import dataclass

@dataclass
class Optional[T]:
    value: T | None

    def __getattr__[V](self, name: str) -> "Optional[V | None]":
        return Optional(getattr(self.value, name, None))

But Pyright and Ty don't recognize the subtypes. What would be the best way to implement this?

🌐
Python.org
discuss.python.org › ideas
Add optional chaining of attributes - Ideas - Discussions on Python.org
May 25, 2023 - Hey everyone! Other languages have the concept of optional chaining (javascript/swift maybe more). It enables developers to easily access nested attributes that might be null. Example of how it could be used. from typing import Optional class B: data: Optional[bool] class A: container: Optional[B] a = A() if data := a?.container?.data: ... To do something similar today. try: if data := a.container.data: ... except (NameError, AttributeError) as e: pass Is this ...
🌐
Python
peps.python.org › pep-0505
PEP 505 – None-aware operators | peps.python.org
The function maybe() returns either a Something instance or a Nothing instance. Similar to the unary postfix operator described in the previous section, Nothing overrides dunder methods in order to allow chaining on a missing value.
🌐
Blogger
deploytonenyures.blogspot.com › 2022 › 11 › python-optional-chaining-revisited.html
Deploy to nenyures: Python Optional Chaining Revisited
I've been thinking again about that Python missing feature (Optional Chaining) I wrote about in this post. It seems like there are no plans to approve the PEP-505 (None aware operators), as there are quite a few opponents to the syntax.
🌐
Python.org
discuss.python.org › ideas
Add optional chaining of attributes - #6 by Declow - Ideas - Discussions on Python.org
May 26, 2023 - As PEP 505 suggests three new operators and that might be a bit much for a single PEP would it be better to create separate PEPs for null coalescing and null aware member access? Or if I move forward with this keep it in a single PEP for these two suggestions?
🌐
CodeArchPedia.com
openillumi.com › home › how to emulate javascript’s optional chaining in python: safe attribute & element access explained
Python Optional Chaining: Safe Attribute & Element Access
December 2, 2025 - For read-only dictionary access, chaining dict.get() is highly recommended, always providing an empty dictionary ({}) as the intermediate default. While Python lacks a native optional chaining operator (PEP 505 is Deferred), Python 3.10+ Pattern ...
🌐
Python
peps.python.org › pep-3134
PEP 3134 – Exception Chaining and Embedded Tracebacks | peps.python.org
Its documentation [10] says that “When an exception X is thrown as a direct result of a previous exception Y, the InnerException property of X should contain a reference to Y.” This property is not set by the VM automatically; rather, all exception constructors take an optional innerException argument to set it explicitly. The __cause__ attribute fulfills the same purpose as InnerException, but this PEP proposes a new form of raise rather than extending the constructors of all exceptions. C# also provides a GetBaseException method that jumps directly to the end of the InnerException chain; this PEP proposes no analog.
Find elsewhere
🌐
Aber
mingshe.aber.sh › en › syntax › optional-chaining
Optional chaining - MíngShé
When trying to access object properties that may not exist, the optional chain operator will make the expression shorter and more concise. https://peps.python.org/pep-0505/
🌐
Delft Stack
delftstack.com › home › howto › python › python optional chaining
Optional Chaining in Python | Delft Stack
October 10, 2023 - Among the features in Python, optional chaining is a safe and concise way of accessing nested object properties.
🌐
Python
peps.python.org › pep-0535
PEP 535 – Rich comparison chaining | peps.python.org
The proposal in this PEP would allow this situation to be changed by updating the definition of element-wise comparison operations in NumPy to return a dedicated subclass that implements the new circuit breaking protocol and also changes the result array’s interpretation in a boolean context to always return False and hence never trigger the short-circuiting behaviour: class ComparisonResultArray(np.ndarray): def __bool__(self): # Element-wise comparison chaining never short-circuits return False def _raise_NotImplementedError(self): msg = ("Comparison array truth values are ambiguous outside " "chained comparisons.
🌐
Hacker News
news.ycombinator.com › item
PEP 505 – None-aware operators (2015) | Hacker News
May 8, 2022 - I'd like to use 'or' more often, but it always makes me stop to think "Could this get passed a falsey value?" I've seen a lot of Python bugs because people used "x or 5" when they needed the much uglier "5 if x is None else x" · Yes. That's how you end up with messes like this one: ...
🌐
JunKangWorld
junkangworld.com › blog › python-optional-chaining-my-3-go-to-patterns-for-2025
Python Optional Chaining: My 3 Go-To Patterns for 2025 | JunKangWorld
August 8, 2025 - Optional chaining is a programming concept that allows you to safely access properties deep within a chain of connected objects without having to explicitly validate that each reference in the chain is valid.
🌐
Medium
medium.com › @guongle › refactoring-series-part-1-optional-chaining-14d69d459b57
Refactoring Series Part 1 — Optional Chaining | by Guong Le | Medium
April 20, 2023 - Optional chaining is not directly supported in Python as a language feature, but there are several ways to achieve similar behavior using existing language constructs.
🌐
Python
peps.python.org › pep-0490
PEP 490 – Chain exceptions at C level | peps.python.org
The PEP was rejected on 2017-09-12 by Victor Stinner. It was decided in the python-dev discussion to not chain C exceptions by default, but instead chain them explicitly only where it makes sense.
🌐
PyPI
pypi.org › project › safebag
Client Challenge
JavaScript is disabled in your browser · Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
Python.org
discuss.python.org › ideas
Introducing a Safe Navigation Operator in Python - Page 4 - Ideas - Discussions on Python.org
October 14, 2023 - I’ve been considering the idea of proposing a new feature in Python - a Safe Navigation Operator, similar to what’s available in languages like JavaScript, Ruby, and C#. Before proceeding with writing a formal PEP, I wan…
🌐
Google Groups
groups.google.com › g › dev-python › c › eMNycEI5kao › m › wiGDkB11AgAJ
[Python-Dev] What's the status of PEP 505: None-aware operators?
This has the advantage of being explicit about what scope the modified rules apply to, rather than simply implicitly being "to the end of the chain of dot/bracket/call operators" It could also be extended to apply, without any additional syntax, to binary operators (result is None if either operand is None) (or None: a + b), for example, could return None if either a or b is none. [I think I proposed this before with the syntax ?(...), the (or None: ...) is just an idea to make it look more like Python.]