More on "with" statement

Rufus V. Smith nospam at nospam
Fri Jul 13 19:53:28 CEST 2001


I went to the FAQ to check the entry about a "with" statement
that is available in other languages.  I can only think of two
reasons to use it.

    1) You're a lazy typist. (Or haven't learned to cut and paste)

    2) You are generally concerned that multiple references to the
     same object with complex, multilevel access might be confusing
    to the reader or not optimized by the compiler.

I used to like the "with" statement in Pascal or VB.  Very useful
for using or setting multiple fields.  However, as programs got large it
could
get difficult knowing if the field was a local, global, or part of a with
block that started several pages back (in Pascal at least.  VB used a
preceding '.', which is a good idea).

A better solution is to assign a temporary reference.  This is possible
in C++:

DeeplyHiddenStruct & rdhs =
&SomeClass.SomeMemberArray[SomeIndex].SomeStruct;

rdhs.Field1 = NewValue;
DoSomethingWith(rdhs.Field2);

etc.  which IMO is easier and cleaner than

SomeClass.SomeMemberArray[SomeIndex].SomeStruct.Field1 = NewValue;
DoSomethingWith(SomeClass.SomeMemberArray[SomeIndex].SomeStruct.Field2);

I don't know if the same thing can be done in VB.

Isn't it possible to do this in Python by simple assigning to a new object
reference?

rdhs = SomeObject.SomeMemberArray[SomeIndex].SomeStruct

The other advantage in the alternate reference is seen when copying
fields from one object to another:

rdest = <some object >
rsrc = <some compatible object>

rdest.field1 = rsrc.field1
rdest.field2 = rsrc.field2
etc.

I am a newbie just cutting my fangs in Python, but if I'm right about this,
perhaps this preferred workaround should be added the FAQ.  If I'm
not...           never mind...









More information about the Python-list mailing list