Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can hasattr go multiple children deep in Python?

Tags:

python

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?

like image 251
Shamoon Avatar asked Feb 11 '26 22:02

Shamoon


1 Answers

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
like image 122
Ned Batchelder Avatar answered Feb 13 '26 15:02

Ned Batchelder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!