Skip to content

Instantly share code, notes, and snippets.

@XoseLluis
Created November 13, 2022 23:16
Show Gist options
  • Save XoseLluis/1e38370965604adc6fa26e6914b0f6cc to your computer and use it in GitHub Desktop.
Save XoseLluis/1e38370965604adc6fa26e6914b0f6cc to your computer and use it in GitHub Desktop.
function motivated by the lack of an Optional Chaining, safe Navigation operator (?, proposed in PEP-505)
def safe_access(fn):
try:
return fn()
except (TypeError, KeyError, IndexError, AttributeError):
return None
# usage:
class Person:
def __init__(self, name, age, profession):
self.name = name
self.age = age
self.profession = profession
class Profession:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def format_profession(self, st1, st2):
return f"{st1}-{self.name}-{st2}"
p1 = Person("Francois", 4, Profession("programmer", 50000))
print(safe_access(lambda: p1.name))
print(safe_access(lambda: p1.city))
print(safe_access(lambda: p1.city.name))
print(safe_access(lambda: p1.profession.salary))
print(safe_access(lambda: p1.profession.format_profession("¡¡", "!!").upper()[:6]))
# invoking a non callable
print(safe_access(lambda: p1.profession.salary()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment