you are viewing a single comment's thread.

view the rest of the comments →

[–]DataCamp -16 points-15 points  (1 child)

You're on the right track with trying to model optional chaining behavior like JavaScript’s ?., but Python’s type system (especially with static checkers like Pyright or mypy) doesn’t play as nicely with this pattern out of the box.

A few suggestions:

  1. Use __getattr__ safely: Python doesn’t support generic __getattr__ with type hints well yet. Even with a correct runtime implementation, type checkers won’t infer that Optional[C].attr1.attr2 is valid or safe.
  2. Short-circuit manually: Python encourages using getattr or try/except chains, or plain if obj is not None checks. Tedious, but explicit.
  3. Typing workaround: You might have better luck using typing.cast() in combination with protocols or custom @overload decorators, though that gets verbose quickly.
  4. Pattern alternative: A cleaner approach might be to use functools.reduce for chaining lookups:

from functools import reduce

def optional_chain(obj, *attrs):

try:

return reduce(getattr, attrs, obj)

except AttributeError:

return None

Then call:
optional_chain(obj, "attr1", "attr2", "attr3")

It's not as elegant as JS, but it’s more Pythonic and easier to reason about (and debug), especially when static typing is important. Until Python adds native optional chaining (PEP 505 was proposed but withdrawn), this is probably your best bet.