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
🌐
Delft Stack
delftstack.com › home › howto › python › python optional chaining
Optional Chaining in Python | Delft Stack
October 10, 2023 - Overall, the above methods are ... we need optional chaining in Python. We can use the try and except approaches and avoid premature optimizations if we know the process and performance problem we solve. Also, we can have a reflection of code by using getattr. Enjoying our tutorials...
🌐
Python.org
discuss.python.org › ideas
Add optional chaining of attributes - Ideas - Discussions on Python.org
May 25, 2023 - 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 ...
🌐
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?

🌐
Blogger
deploytonenyures.blogspot.com › 2022 › 11 › python-optional-chaining-revisited.html
Deploy to nenyures: Python Optional Chaining Revisited
Thanks to looking into this topic again I've come across 2 very interesting ideas. One is the Maybe pattern, and its implementation in Python. The other one quite blew me away. An implementation of PEP-505 as a polyfill. So, how can you do that? Well, you can hook into the modules import process and do crazy stuff with them like transforming their source code before python compiles them to bytecodes.
🌐
Mooncafealcona
mooncafealcona.ca › imgen452 › python-optional-chaining
python optional chaining
December 28, 2024 - Optional chaining can be effectively combined with other operators and techniques: With in operator: Check for the existence of a key in a dictionary before accessing the value: value = my_dict?.get('key') With indexing: Access elements in lists or tuples safely: element = my_list?[0] In conditional expressions: Elegantly handle optional values within conditional statements: result = value?.upper() if value else "No Value" Python's optional chaining is a significant enhancement to the language, empowering developers to write more concise, readable, and robust code.
🌐
Python.org
discuss.python.org › ideas
Add optional chaining of attributes - #6 by Declow - Ideas - Discussions on Python.org
May 26, 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 typi…
🌐
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 - Python's safe attribute & element access, like JS optional chaining. Prevent NoneType and KeyError. Master robust coding using dict.get() and getattr().
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/
🌐
Redgablesdeli
redgablesdeli.ca › educationai › python-optional-chaining
python optional chaining
December 13, 2024 - Optional chaining uses the . operator followed by a question mark ?. If the left-hand side of the ?.
🌐
Bornmidwives
bornmidwives.ca › vertic328 › python-optional-chaining
python optional chaining
October 16, 2024 - Optional chaining with method calls: You can also use optional chaining to call methods on objects that might be None: my_object = None result = my_object?.method() # This will return None without raising an error · Chaining multiple attributes: You can chain multiple attributes using ?. to navigate deeper into nested objects. ... Python's optional chaining operator is a valuable tool for handling potential None values, leading to cleaner, more readable, and more robust code.
🌐
Python
peps.python.org › pep-0505
PEP 505 – None-aware operators | peps.python.org
Proposal: Optional Chaining for JavaScript (https://github.com/tc39/proposal-optional-chaining) [5] Associated scripts (https://github.com/python/peps/tree/master/pep-0505/) This document has been placed in the public domain. Source: https://github.com/python/peps/blob/main/peps/pep-0505.rst ·
🌐
Myobservatoryhill
myobservatoryhill.ca › Trending › python-optional-chaining
python optional chaining
November 15, 2024 - Python's optional chaining, introduced in version 3.8, provides a safe and elegant way to access attributes and items within nested structures without the risk of dreaded AttributeError or KeyError.
🌐
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
🌐
Refactoring.Guru
refactoring.guru › home › design patterns › chain of responsibility › python
Chain of Responsibility in Python / Design Patterns
January 1, 2026 - It also declares a method for executing a request. """ @abstractmethod def set_next(self, handler: Handler) -> Handler: pass @abstractmethod def handle(self, request) -> Optional[str]: pass class AbstractHandler(Handler): """ The default chaining behavior can be implemented inside a base handler class.
🌐
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.
🌐
Wikipedia
en.wikipedia.org › wiki › Safe_navigation_operator
Safe navigation operator - Wikipedia
1 month ago - Optional chaining operator, subscript operator, and call: