Created
November 13, 2022 23:16
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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