Favorite non-python language trick?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Jun 26 06:30:15 CEST 2005


On Sat, 25 Jun 2005 23:08:10 +0000, Bengt Richter wrote:

> On Sun, 26 Jun 2005 04:08:31 +1000, Steven D'Aprano <steve at REMOVETHIScyber.com.au> wrote:
> 
>>On Fri, 24 Jun 2005 15:47:45 -0700, James Stroud wrote:
>>
>>> On Friday 24 June 2005 05:58 am, Steven D'Aprano wrote:
>>>> 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.
>
> How do you like the following?
>  >>> color = type('',(),{})() # an instance that will accept attributes
>  >>> vars(color)
>  {}
> 
> The single line replacing
>      """
>      with colour do begin
>      red := 0; blue := 255; green := 0;
>      end;
>      """
> follows:
>  >>> vars(color).update(red=0, blue=255, green=0)


The point is that a hypothetical "with" block would have to allow
arbitrary access to dotted names: getting, setting, deletion, and method
calling, not just one very limited form of keyword assignment.

I understand how to manipulate __dict__ as an more complicated (dare I say
obfuscated?) way of assigning to object attributes.


[snip]

> We can clear those attributes from the instance dict:
>>>> vars(colour).clear()
>>>> vars(colour)
> {}

Which has the unfortunate side effect of also destroying any other
instance attributes.


>>you might do this:
>>
>>with myobject:
>>    # read a class attribute
>>    print .__class__.myattribute
>>    # set an instance attribute
>>    .widget.datapoints[.collector] = .dispatcher(.widget.current_value)
>>
> 
> def mywith(o=myobject):
>      # read a class attribute
>      print o.__class__.myattribute
>      # set an instance attribute
>      o.widget.datapoints[o.collector] = o.dispatcher(o.widget.current_value)
> mywith()

[snip]

> Is a one-character prefix to the dot objectionable?

That's a good workaround, subject to namespace pollution issues, and one
that I'm aware of. Although do you really want to be creating a unique
function definition every time you want to use the with idiom?

I'm not about to stop using Python because of the lack of Pascal-like
"with" blocks. It is a nice feature to have, but I'm aware that Guido
prefers explicit to implicit and "with" is extremely implicit. 



-- 
Steven.




More information about the Python-list mailing list