Python "with"
Colin J. Williams
cjw at sympatico.ca
Mon Sep 17 17:50:10 EDT 2007
Ivan Voras wrote:
> Hi,
>
> I'm looking for a construct that's similar to (Turbo) Pascal's "with"
> statement. I read about the Python's new "with" statement, but I was
> dissapointed to learn that it does something different (I still don't
> see how it's better than try..except..finally, but that's not my question).
>
> Is there something similar to what I want that's Pythonic enough?
>
> (If you're not familiar with Pascal, here's how it works:
>
> with some.big.structure.or.nested.objects.element do begin
> member1 := something;
> member2 := something;
> end;
>
> which exactly translates to this equivalent:
>
> some.big.structure.or.nested.objects.element.member1 := something;
> some.big.structure.or.nested.objects.element.member2 := something;
>
> i.e. it's a wrist-saver. I think a similar feature exists in C99, for
> structs.
>
> I know it can be almost always done by using a temporary variable:
>
> tmp = some.big.structure.or.nested.objects.element
> tmp.member1 = something
> tmp.member2 = something
>
> but this looks ugly to me.)
>
>
The "with" statement in Pascal was a neat feature to use with records.
Unfortunately, in Python 2.5, "with" has a different use.
Colin W.
More information about the Python-list
mailing list