More on "with" statement

Levente Sandor nospam at newsranger.com
Fri Jul 13 23:55:01 EDT 2001


If you absolutely need a 'with' statement...

import re
def with(object, statements):
""" 'with' for the very lazy programmer :) :) :)
Someone might prefer Ctrl+C, Ctrl+V, ... instead."""
exec(re.sub('\B\.', '%s.' % object, statements))

#--- example usage:
class a_class: pass
an_instance_of_a_class_with_a_very_long_name = a_class()
with('an_instance_of_a_class_with_a_very_long_name', '''
var1 = 111
var2 = 222
var3 = 333
var4 = 444
var5 = 555
''')
with('an_instance_of_a_class_with_a_very_long_name', '''
print .var1, .var2, .var3, .var4, .var5
''')

Levi

In article <3b4f3602$0$15367 at wodc7nh6.news.uu.net>, Rufus V. Smith says...
>
>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