If I have node.child1.child2, can I use hasattr(node, 'child1.child2') effectively? Will it error if there's no child1 or simply return false?
hasattr doesn't take a dotted name like that and navigate down attribute chains. But you can write a function to do it:
def get_deep_attr(obj, attrs):
for attr in attrs.split("."):
obj = getattr(obj, attr)
return obj
def has_deep_attr(obj, attrs):
try:
get_deep_attr(obj, attrs)
return True
except AttributeError:
return False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With