a = b = 1 just syntactic sugar?

Ed Avis ed at membled.com
Thu Jun 5 17:33:17 EDT 2003


Steven Taschuk <staschuk at telusplanet.net> writes:

>    class config(object):
>        def command_setcolour(self, value):     
>            # ...
>        # etc.
>        def perform(self, command, arg):
>            getattr(self, 'command_' + command)(arg)
>
>whereupon reading the configuration is just
>
>    cfg = config()
>    for cmd, arg in commands:
>        cfg.perform(cmd, arg)

That does look pretty reasonable I must admit.  I didn't think of such
a solution (pasting together 'command_' and the string read from
input) because I was thinking in a C-ish kind of way.  Of course in
Python there is no obstacle to writing such code, except maybe a small
speed reduction.

>>It's just frustrating not to be able to write the function
>>definitions inline, in the obvious place, especially when they might
>>be only one line each and there is the 'lambda' keyword which at
>>first looks so inviting and useful.
> 
>Yes, I see your point.  However, I don't think anything can be done
>about it without throwing away the present use of indentation for
>block delimiting.

I don't think this is true; if lambda were modified to allow
assignment, for example, the whole expression would still fit on one
line.  (Of course, a multi-line lambda which used indentation to show
the function body would be welcome...)

>Also, a scheme such as the above, with an explicit configuration
>object, seems quite natural to me.

It works well in this case.  However this is just one example of where
you might want to use anonymous functions, and have to use something
else because of lambda's shortcomings.  Another case was in an
application I was writing a while back where I wanted to compare two
data structures and generate a 'diff'.  The function was to return
None if its two arguments were identical, otherwise a function which
could be applied to the first data structure to generate the second.
I started writing the code in a recursive, moderately 'functional'
style to generate this diff function, but was disappointed to find out
that such a technique could never work in Python (as it currently
stands).

(And yes, I did eventually find a different way to do the job, but it
was IMHO not as clear and not as maintainable.  There are always
workarounds for a missing language feature - you could write a whole
program without using the 'if' statement - but while in some cases the
alternative style may be more obvious and more idiomatic, it isn't
always.)

Anyway, I think we have established an answer to the original question
I asked, which was can you do assignment inside an expression.  The
answer is not really, although you can do a lot of things like setattr
or setdefault which have similar effects to assignment but aren't.

-- 
Ed Avis <ed at membled.com>




More information about the Python-list mailing list