Skip to content

Instantly share code, notes, and snippets.

@hqhs
Created April 11, 2018 15:26
Show Gist options
  • Save hqhs/215316ba63815ccb48f55532cc7d37ab to your computer and use it in GitHub Desktop.
Save hqhs/215316ba63815ccb48f55532cc7d37ab to your computer and use it in GitHub Desktop.
from functools import reduce
class A:
def __init__(self, obj_list):
self.obj_list = obj_list
class B:
def __init__(self, number):
self.number = number
def _getitem(obj, item):
try:
return obj.__dict__.__getitem__(item)
except AttributeError:
return obj.__getitem__(item)
def _getattrd(obj, default, *args):
try:
return reduce(_getitem, args, obj.__dict__)
except (KeyError, AttributeError, TypeError):
return default
list_of_bs = [B(1), B(2), B(3)]
obj_a = A(list_of_bs)
print(_getattrd(obj_a, 'default_value', 'obj_list', 2, 'number'))
# output:
# 3
print(_getattrd(obj_a, 'default_value', 'obj_list', 'no_attr', 4))
# output:
# default_value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment