Hi all, Today I was thinking about a problem I often encounter. Say that I have (seems I often do!) a deeply nested object, by which I mean object within object with object, etc.
For example: x = some.deeply.nested.object.method(some.other.deeply.nested.object.value) Well, that's extreme but I've worked with code approaching that level of nested-ness. Now, consider two scenarios: 1. You need to call this thing many times with different arguments, so you wind up with: x = some.deeply.nested.object.method(some.other.deeply.nested.object.value1) y = some.deeply.nested.object.method(some.other.deeply.nested.object.value2) z = some.deeply.nested.object.method(some.other.deeply.nested.object.value3) 2. You call it inside a loop: for item in some_iterable: x = some.deeply.nested.object.method(some.other.deeply.nested.object.value) For one thing, I find the long lines unattractive at best and error-prone at worst, especially if I also have some.other.deeply.nested.object.method that I might confuse with the first. To make it look better I might do this: _o = some.deeply.nested.object _o.method(_o.value) which is fine, I suppose. Then, putting on my company hat, I remembered that, from VBA, you could do this: with some.deeply.nested.object .method(.value) end with I like the structure of this, since the subordinate block can be indented, which makes it stand out. Also, it avoids temporary variables. So, I was thinking of how to get close to this in Python. I came up with two approaches: 1. _o = some.deeply.nested.object if 1: _o.method(_o.value) The "if 1:" forces me to indent the subordinate code, which sets it apart from the surrounding code. Note that I cannot just indent because I feel like it since Python is persnickety about indentation. 2. for _o in [some.deeply.nested.object]: _o.method(_o.value) The "for..." sets up the iterator and forces me to indent the subordinate code. As an aside, approach 1 generates less byte-code since approach 2 sets up loop machinery which you don't really need in this case. I have a couple of questions: 1. If you had to choose between approaches 1 and 2, which one would you go for, and why? 2. What other techniques have you used in such a situation? -- Gerald Britton -- http://mail.python.org/mailman/listinfo/python-list