Re: Comments merging, pass 2
will guaraldi <[email protected]>
| Newsgroups | gmane.comp.web.pyblosxom.devel |
|---|---|
| Message-ID | <[email protected]> |
On Sat, 11 Dec 2004, Steven Armstrong wrote:
>>
>> Here I think is the formula that is really unpythonic, which you seem
>> to use all the time. What does this mean? It takes me a hell of a long
>> time to figure it out, and I don't do anything besides write and read
>> python all day. Why not write:
>>
>> if form.has_key('url'):
>> url = form['url'].value
>> else:
>> url = ''
>
> In JavaScript, Java and C you can do neat things like:
>
> var result = (condition)? "hello" : "world";
>
> Which returns "hello" if condition is True and "world" otherwise.
>
> As I learned at
> http://diveintopython.org/power_of_introspection/and_or.html#d0e9975
>
> result = (condition and ['hello'] or ['world'])[0]
> is the python way to do that safely.
Well, I'm with Bill on this one. Yes, there's a section in the Dive Into
Python book that talks about imitating ternary operators, but he then
says:
"By now, this trick may seem like more trouble than it's worth. You could,
after all, accomplish the same thing with an if statement, so why go
through all this fuss? Well, in many cases, you are choosing between two
constant values, so you can use the simpler syntax and not worry, because
you know that the a value will always be true. And even if you need to use
the more complicated safe form, there are good reasons to do so. For
example, there are some cases in Python where if statements are not
allowed, such as in lambda functions."
In this case, since the values you're doing things with are not constants
and there's no really good reason to do what you've done, I would think
it's better to do it with an if/else.
You make the statement that "it's the Python way to do things". I would
infer from Dive Into Python that this is the way to imitate the ternary
operator, but the resulting code is not necessarily the Python way of
doing things.
I think what you've got is less legible than an if/else construct, so I
would vote for the if/else. Remember, other people have to maintain this
code.
It's interesting to note that later on in Bill's email he mis-reads
another ternary ... well, I want to use the word monstrosity here, but I
don't want to be insulting... Anyhow you point out that he's misread it.
But the reason he misread it is that it's very hard to read and definitely
hard to figure out what the behavior you intended was supposed to be.
/will
-------------------------------------------------------
SF email is sponsored by - The IT Product Guide
Read honest & candid reviews on hundreds of IT Products from real users.
Discover which products truly live up to the hype. Start reading now.
http://productguide.itmanagersjournal.com/