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?

🌐
GitHub
github.com › topics › optional-chaining
optional-chaining · GitHub Topics · GitHub
python finance django option-pricing tradier-api options-trading optional-chaining
🌐
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...
🌐
blog
see-mike-out.github.io › blog › python › 2022 › 04 › 18 › optional-chaining-in-python.html
Optional Chaining in Python | blog
April 18, 2022 - def getDictValue(d, k, alt=None): # @d: a dictionary # @k: a key chain (str ("a.b.c") or list ["a", "b", "c"]) # @alt: an alternative value to return when the key is not in the dict # (default: None) # if the key chain @k is str, convert to a list if type(k) == str: k = k.split(".") # if the first key in @k is not in the dict @d, return @alt if d.get(k[0]) is None: return alt # else if the key chain @k's length is 1, return its value # implicitly, it assumes that the value is found elif len(k) == 1: return d[k[0]] # else (recursion) else: return getDictValue(d[k[0]], k[1:], alt)
🌐
GitHub
github.com › nicwolff › if_
GitHub - nicwolff/if_: Optional chaining for Python
Call if_() with a Python expression, and chain attribute and item accessors on the return value, ending with ._.
Author   nicwolff
🌐
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 ...
🌐
Delft Stack
delftstack.com › home › howto › python › python optional chaining
Optional Chaining in Python | Delft Stack
October 10, 2023 - This article describes the methods we can follow when we adapt to the optional chaining in Python. Adapting to one of the methods below will make it easy to use optional chaining in Python instead of JavaScript.
🌐
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.
Find elsewhere
🌐
GitHub
github.com › tc39 › proposal-optional-chaining › issues › 68
Using the name "safe-navigation" operator instead of "optional-chaining" · Issue #68 · tc39/proposal-optional-chaining
July 7, 2018 - Conditional Optional-chaining more closely resembles one of the hacks people used in Javascript to obtain the same effect: ((object || {}).property1 || {}).property2 || null where chaining could either refer to the chain of conditions which must be met, or the chain in the sense of the object path.
Published   Jul 07, 2018
🌐
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…
🌐
Python
peps.python.org › pep-0505
PEP 505 – None-aware operators | peps.python.org
Proposal: Nullish Coalescing for JavaScript (https://github.com/tc39/proposal-nullish-coalescing) [4] 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.
🌐
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
🌐
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 - While Python lacks a native optional chaining operator (?.) like JavaScript, these idiomatic patterns are more powerful and explicit, preventing common bugs like AttributeError and KeyError.
🌐
Bornmidwives
bornmidwives.ca › vertic328 › python-optional-chaining
python optional chaining
October 16, 2024 - By utilizing optional chaining, you can avoid common pitfalls associated with None values and write more efficient and reliable Python applications. ... This article is inspired by the discussions on GitHub related to optional chaining in Python.
🌐
Maplecrestinn
maplecrestinn.ca › post › python-optional-chaining
Maplecrestinn
October 16, 2024 - By utilizing optional chaining, you can avoid common pitfalls associated with None values and write more efficient and reliable Python applications. ... This article is inspired by the discussions on GitHub related to optional chaining in Python.
🌐
E1515
e1515.com.tw › post › python-optional-chaining
python optional chaining
December 11, 2024 - It’s particularly useful in ... optional chaining is a powerful feature that significantly improves the safety and readability of code that interacts with potentially incomplete data structures....
🌐
Wikipedia
en.wikipedia.org › wiki › Safe_navigation_operator
Safe navigation operator - Wikipedia
1 month ago - In object-oriented programming, the safe navigation operator (also known as optional chaining operator, safe call operator, null-conditional operator, null-propagation operator) is a binary operator that returns null if its first argument is null; otherwise it performs a dereferencing operation ...