Style question: Nicknames for deeply nested objects

Stephen Hansen me+list/python at ixokai.io
Sun Jan 30 13:23:08 EST 2011


On 1/30/11 9:51 AM, Gerald Britton wrote:
> 1. If you had to choose between approaches 1 and 2, which one would
> you go for, and why?

Neither. Ideally, I'd tweak the API around so the deeply nested
structure isn't something I need to access regularly. But! If you can't
do that, I'd do something like:

--- start
from contextlib import contextmanager

class Item(object): pass

deeply = Item()
deeply.nested = Item()
deeply.nested.thing = Item()

@contextmanager
def my(thing):
    yield thing


with my(deeply.nested.thing) as o:
    o.hello = 1

print deeply.nested.thing.hello
--- end

That's a dummy context-manager which basically does nothing: it just
"abuses" the context manager protocol to basically make a local variable
and indent its usage. Its really just a run-around and slightly less
efficient to do:

>    _o = some.deeply.nested.object
>    _o.method(_o.value)

But with the whitespace added on.

Personally, I'd usually just make a local variable and skip any tricks.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 487 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20110130/3eea3a2c/attachment-0001.sig>


More information about the Python-list mailing list