3

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 ..

1 Answer 1

10

Use reduce():

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

or a simple loop:

foo = bundle.obj
for field in fields:
    foo = getattr(foo, field)
Sign up to request clarification or add additional context in comments.

6 Comments

I feel like every day I learn about another built-in function that is incredibly useful. That Guido is one smart benevolent dictator :)
@JasonSperske: Actually, Guido can't remember who convinced him to add reduce in the early days, but he's wanted to get rid of it ever since. And many of the other core devs agree with him. They hate it with a passion, and in the 3.0 transition, were just barely persuaded to move it to functools and just stop talking about it instead of removing it entirely. (Personally, I think there are some cases where reduce makes things more readable—rare, but this is definitely one of them.)
@abarnert: No doubt it was one of those obnoxious Lisp people. :D (I'd say "one of us" except that I never wrote much Lisp, even when I was hanging out with the AI grad students....) Hasn't there been a lot of grumbling about map as well?
@JasonSperske: I think a lot of it is a matter of taste and a knowledge of history. Both map and reduce came out of various functional languages, and lots of bits of Python are stolen I mean borrowed from other languages as well. Getting the right mix of ideas with workable syntax and so on, well, that's where "taste" comes in. Python has it, perl ... not so much. :D
@torek: A lot less. Guido did originally suggest getting rid of map and filter when he added comprehensions, but since various people have started using map to contrast with reduce (as in "not all functional tools are as useless as reduce—look at map, which everyone loves as a builtin") he's come around to their way of thinking.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.