Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traversing objects in python

Tags:

python

How can I write this code without repeating myself indefinitely?

fields = row.split('__')

if len(fields) == 1:
    foo = getattr(bundle.obj, fields[0])
elif len(fields) == 2:
    foo = getattr(getattr(bundle.obj, fields[0]), fields[1])
elif len(fields) == 3:
    foo = getattr(getattr(getattr(bundle.obj,
                            fields[0]), fields[1]), fields[2])
# etc ..
like image 251
user2548487 Avatar asked May 21 '26 23:05

user2548487


1 Answers

Use reduce():

foo = reduce(getattr, fields, bundle.obj)

or a simple loop:

foo = bundle.obj
for field in fields:
    foo = getattr(foo, field)
like image 100
Martijn Pieters Avatar answered May 23 '26 13:05

Martijn Pieters



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!