Skip to content

Instantly share code, notes, and snippets.

@koaning
Last active November 29, 2025 19:53
Show Gist options
  • Select an option

  • Save koaning/14045b0f47f3c4f2c727c6c74fca1fc3 to your computer and use it in GitHub Desktop.

Select an option

Save koaning/14045b0f47f3c4f2c727c6c74fca1fc3 to your computer and use it in GitHub Desktop.
class Maybe:
def __init__(self, obj):
self._obj = obj
def __getattr__(self, name):
if self._obj is None:
return Maybe(None)
try:
result = getattr(self._obj, name)
return Maybe(result)
except AttributeError:
return Maybe(None)
def __bool__(self):
return self._obj is not None
def __repr__(self):
return "Maybe()"
def collect(self):
return self._obj
class User:
def __init__(self, name, email):
self.name = name
self.email = email
user = User("John Doe", "[email protected]")
if Maybe(user).foo:
print("bar")
@ateshakan
Copy link

that is such an elegant way to approach optional chaining. we use pydantic to handle cases but still not that clean and elegant since you need use a walrus operator to make linter happy.

# sth like
if (article := research.article_gathered) and (attachment := article.attachment):
    print(attachment.attachment_id)
else:
...

Apparently the ?. operator was actually proposed (PEP 505) and rejected multiple times.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment