History of 'self' and why not at least 'my'?

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Jan 11 07:32:52 EST 2002


Giorgi Lekishvili <gleki at gol.ge> wrote in news:3C3F4D4B.5922ABED at gol.ge:

> I would like rather to have something akin of Pascal's or VB's 'with',
> e.g., with self:
>     bla1,
>     bla2
>     ...
> 
> Grtz,
> Giorgi
> 

The FAQ describes why a "with" statement as you describe it doesn't work in 
Python: see http://www.python.org/doc/FAQ.html#6.31

However, what it doesn't really cover is that a common use of "with" is to 
reduce a complicated reference to an object:
e.g. with obj[expression].field[exp].etc:
    	    	a = 5
    	    	b = 6

If this is what you are trying to do, then Python already has a statement 
to handle this, namely 'assignment':
    	    	w = obj[expression].field[exp].etc
    	    	w.a = 5
    	    	w.b = 6
The same technique can be used at a local level to reduce the overhead of 
typing self:
    	s = self
    	s.a, s.b, s.c = 1, 2, 3

This compares quite favourably with those C++ developers who insist on 
naming every member variable with the prefix 'm_'.

If you really want "with", try this:
>>> def with(self, **args):
...     self.__dict__.update(args)
...
>>> class C:
...     def test(self):
...             with(self,
...                     a=1, b=2,
...                     c=3)
...
>>> x = C()
>>> x.test()
>>> dir(x)
['a', 'b', 'c']
>>>
-- 
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