'with' statement in python ?
Duncan Booth
duncan at NOSPAMrcp.co.uk
Tue Jun 26 04:14:50 EDT 2001
asgard <asgard at hellnet.cz> wrote in news:mailman.993497019.14391.python-
list at python.org:
> could be written as
>
> with self:
> a=1
> b=2
>
> ? Of course it would work with other names too.
>
Does this mean "self.a=1; self.b=2" or are either of a and b local or
global variables?
There are two main uses for with. In your example you are using with simply
to avoid writing 'self.' in front of each member reference. The problem is
that in Python you cannot tell until runtime whether self has attributes a
and b. You could assume that all variable references inside the 'with'
became prefixed with 'self.', but then you couldn't access any values that
weren't in your object. So simply as a way to save yourself typing 'with'
won't work.
The other use for with is to precalculate some complicated reference:
with some.thing[or](other):
foo = 5 * bar
bar += 1
Python already has an equivalent way to do this:
t = some.thing[or](other)
t.foo = 5 * t.bar
t.bar += 1
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list