Favorite non-python language trick?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sat Jun 25 21:49:21 EDT 2005


On Sat, 25 Jun 2005 15:44:14 -0400, Nicolas Fleury wrote:

> Steven D'Aprano wrote:
>> One of the things I liked in Pascal was the "with" keyword. You could
>> write something like this:
>> 
>> with colour do begin
>> red := 0; blue := 255; green := 0;
>> end;
>> 
>> instead of:
>> 
>> colour.red := 0; colour.blue := 255; colour.green := 0;
>> 
>> Okay, so maybe it is more of a feature than a trick, but I miss it and it
>> would be nice to have in Python.
>> 
> 
> With PEP343 (I guess in Python 2.5), you will be able to do something like:
> with renamed(colour) as c:
>      c.red = 0; c.blue = 255; c.green = 0
> 
> I think however it is bad.  Better solutions to me would be:
> 
> colour.setRgb(0, 255, 0)

But that is no help, because the setRgb method will be implemented as

def setRgb(r, g, b):
    self.red = r; self.green = g; self.blue = b

which is exactly the usage case for a with statement:

def setRgb(r, g, b):
    with self:
        .red = r; .green = g; .blue = b

> or
> 
> c = myVeryLongNameColour
> c.red = 0; c.blue = 255; c.green = 0

Namespace pollution. It might not matter if c is a temporary variable
inside a function or method, but it does matter if your top-level code is
full of such constructs. Or for that matter, your interactive Python
session.


-- 
Steven.




More information about the Python-list mailing list