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 ..
Use reduce():
foo = reduce(getattr, fields, bundle.obj)
or a simple loop:
foo = bundle.obj
for field in fields:
foo = getattr(foo, field)
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