Re: case/switch statement?

2005-06-18 Thread Peter Hansen
D H wrote:
> Peter Hansen wrote:
[some stuff Doug didn't like]

> I don't think you could have misread my simple suggestion to you any 
> more completely than you did.

Sorry, I'll try harder next time.

-Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-17 Thread D H
Peter Hansen wrote:
> D H wrote:
> 
>> Peter Hansen wrote:
>>
>>> With a case statement, on the other hand, you *know* that it must be 
>>> just simple conditionals (a series of x == some_constant tests), so 
>>> you don't need to look at all the cases, just the one that interests 
>>> you.
>>
>>
>> Since you and Steve Holden agree that a case statement is useful, why 
>> don't you propose it for python, or add it to the wiki page for Python 
>> 3000.
> 
> 
> Two simple reasons.
> 
> 1. You forgot my previous comment that "in current Python the equivalent 
> approach is, of course, a dictionary of some kind, though it's arguable 
> whether this is as clean in many cases as a case statement would be."

I didn't forget that.  I never read it, and I don't see the relevance to 
my suggestion.  Now that I've read it, I would hardly call using a 
dictionary as a switch statement, the "equivalent".  The fact that 
people use a dictionary as a conditional is a python wart.

> 2. Just because something is "useful" doesn't mean it should be added to 
> Python.  The bar should be set much higher, and should include at least 
> "and significantly better than any existing alternative way of doing the 
> same thing."  Now go read point 1 again... ;-)

Now go read my message again.  I made a suggestion to you.  I didn't say 
that a switch statement should be added myself.  I would never propose 
that because the chances of it being added are microscopic.


> My point was not to suggest that I want a case statement in Python, nor 

Neither was the MY point, which you seem to have inferred.

> even that a case statement is a good thing to have in a language (though 
> it might be... it's not my place to say).  My point was simply to point 
> out that performance is not the only reason to use a case statement.

I don't think you could have misread my simple suggestion to you any 
more completely than you did.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding Word and switch focus to it

2005-06-15 Thread John Henry
I tried the first part and works like a charm.  I will read the post
you cited.

Thanks,

--
John

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Finding Word and switch focus to it

2005-06-15 Thread Hughes, Chad O
Consider reading this post. It highlights how to do what you want:
http://mail.python.org/pipermail/python-win32/2002-April/000322.html

Chad

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of
John Henry
Sent: Wednesday, June 15, 2005 3:21 PM
To: python-list@python.org
Subject: Finding Word and switch focus to it


Does anybody know how to find an opened copy of Word and switch focus to
it, wait until Word is closed, before continuing my Python script? I
tried to search for the answer from Google and nothing stands out.

Running under Windows XP.

Thanks,

--
John

-- 
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Finding Word and switch focus to it

2005-06-15 Thread Hughes, Chad O
The first part is easy. I will have to think about the second part. To
find an opened copy of Word and switch focus to it do the following:

from win32com.client import Dispatch
word = Dispatch('Word.Application')
wdWindowStateNormal = 0
if len(word.Documents):
  word.Activate()
  if word.WindowState != wdWindowStateNormal:
word.WindowState = wdWindowStateNormal  
 
-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of
John Henry
Sent: Wednesday, June 15, 2005 3:21 PM
To: python-list@python.org
Subject: Finding Word and switch focus to it


Does anybody know how to find an opened copy of Word and switch focus to
it, wait until Word is closed, before continuing my Python script? I
tried to search for the answer from Google and nothing stands out.

Running under Windows XP.

Thanks,

--
John

-- 
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Finding Word and switch focus to it

2005-06-15 Thread John Henry
Does anybody know how to find an opened copy of Word and switch focus
to it, wait until Word is closed, before continuing my Python script?
I tried to search for the answer from Google and nothing stands out.

Running under Windows XP.

Thanks,

--
John

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-14 Thread Peter Hansen
D H wrote:
> Peter Hansen wrote:
>> With a case statement, on the other hand, you *know* that it must be 
>> just simple conditionals (a series of x == some_constant tests), so 
>> you don't need to look at all the cases, just the one that interests you.
> 
> Since you and Steve Holden agree that a case statement is useful, why 
> don't you propose it for python, or add it to the wiki page for Python 
> 3000.

Two simple reasons.

1. You forgot my previous comment that "in current Python the equivalent 
approach is, of course, a dictionary of some kind, though it's arguable 
whether this is as clean in many cases as a case statement would be."

2. Just because something is "useful" doesn't mean it should be added to 
Python.  The bar should be set much higher, and should include at least 
"and significantly better than any existing alternative way of doing the 
same thing."  Now go read point 1 again... ;-)

My point was not to suggest that I want a case statement in Python, nor 
even that a case statement is a good thing to have in a language (though 
it might be... it's not my place to say).  My point was simply to point 
out that performance is not the only reason to use a case statement.

-Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-13 Thread D H
Peter Hansen wrote:
> With a case statement, on the other hand, you *know* that it must be 
> just simple conditionals (a series of x == some_constant tests), so you 
> don't need to look at all the cases, just the one that interests you.

Since you and Steve Holden agree that a case statement is useful, why 
don't you propose it for python, or add it to the wiki page for Python 3000.

Here is the syntax the developers of your favorite language boo ( 
http://boo.codehaus.org/ ) are using:

given x:
 when 1:
 ...
 when 2:
 ...
 otherwise:
 ...


must-stop-hyphenating-ly y'rs
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-13 Thread Philippe C. Martin
Any speed issue ?


[EMAIL PROTECTED] wrote:

> Philippe C. Martin wrote:
>> Leif K-Brooks wrote:
>>
>> > Joe Stevenson wrote:
>> >> I skimmed through the docs for Python, and I did not find anything
>> >> like
>> >> a case or switch statement.  I assume there is one and that I just
>> >> missed it.  Can someone please point me to the appropriate document,
>> >> or
>> >> post an example?  I don't relish the idea especially long if-else
>> >> statements.
>> >
>> > If you really want one, you could use
>> > <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410692>.
>>
>> I _love_ Python!
> 
> 
> Well, if you loved that, here's something even more evil.  This was
> Bengt Richter's original idea that Cliff Wells and I improved upon.
> First define some functions and classes:
> 
> . _cache = {}
> .
> . class _BaseCaseException(Exception):
> . pass
> .
> . def switch(v):
> . if v not in _cache:
> . class _CaseException(_BaseCaseException):
> . pass
> . _cache[v] = _CaseException
> . raise _cache[v]
> .
> . def case(v):
> .     if v not in _cache:
> . class _CaseException(_BaseCaseException):
> . pass
> . _cache[v] = _CaseException
> . return _cache[v]
> .
> . default = _BaseCaseException
> 
> 
> Then you can define a switch statement like this:
> 
> . x = 2
> .
> . try: switch(x)
> .
> . except case(1):
> . print "Case 1"
> .
> . except case(2):
> . print "Case 2"
> .
> . except case(3):
> . print "Case 3"
> .
> . except default:
> . print "Default"
> .
> . except NameError:
> . print "You can still catch regular exceptions like NameError"
> 
> 
> 
> I-love-Python-too-but-this-isn't-why-ly yr's,
> 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-13 Thread Skip Montanaro

Terry> Yeah, and I find this even more so:

Terry> case =  {
Terry> 5: do_this,
Terry> 6: do_that,
Terry> }
Terry> case.get(x, do_default)()

Terry> Which is looking pretty close to a case statement, anyway.

Sure, modulo namespace issues.

Skip
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-13 Thread Terry Hancock
On Sunday 12 June 2005 07:33 am, Dan Sommers wrote:
> > There is no case statement in Python. If you don't care about
> > readability, one alternative is to use a dictionary:
> 
> > case = {5: do_this, 6: do_that}
> > case.get(x, do_something_else)()
> 
> I find this very readable.  YMMV.

Yeah, and I find this even more so:
case =  {
5: do_this,
6: do_that,
}
case.get(x, do_default)()

Which is looking pretty close to a case statement, anyway.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-13 Thread Steve Holden
Peter Hansen wrote:
> Chinook wrote:
> 
>>On Sun, 12 Jun 2005 17:19:06 -0400, Peter Hansen wrote:
>>
>>>Case statements are actually more suitable in many cases even when 
>>>performance is not a goal for reasons of *readability*.
>>>
>>>When reading an if statement, you have to scan down through effective 
>>>each statement attempting to find the case in which you are interested. 
>>> Some cases can be compound.  The nested ifs can get confused with the 
>>>surrounding ones (in Python or a language with explicit block 
>>>delimiters).  The cases are often not written in any particular order, 
>>>or they are ordered *for* performance reasons, but in ways that make it 
>>>harder to "scan".
>>
>>The problem I do see is your apples and oranges argument.  You are equating 
>>at the extreme, "compound" if conditions with "_simple_" case statement 
>>conditionals.  Yet you are leaving out of your argument the transition from 
>>the former to the latter.  If mapping one to the other is simple then the 
>>readability is no harder with if statements.  
> 
> 
> I dispute that, and believe you've misunderstood my core point.  It's 
> not anything to do with "equivalence" between the two approaches.  It's 
> that if you see a set of if/else statements, you have to look at all of 
> them to understand completely what's happening.  (I mean the structure 
> of the if/else... the conditionals, not the contents of the blocks.) 
> With a case statement, on the other hand, you *know* that it must be 
> just simple conditionals (a series of x == some_constant tests), so you 
> don't need to look at all the cases, just the one that interests you.
> 
> So it's not a comparison between two ways of writing the same thing, 
> it's about the fact that with a case statement there are many things you 
> *cannot* write, so reading one is much easier than reading a similarly 
> sized compound if/else.
> 
While this is how case statements *tend* to be used, it is of course 
trivially possible to rewrite any if-then as a case:

 case :
 value True:
 ...
 value False:
 ...

This would, of course, be a perversion of the purpose of the case 
statement, and I agree with you that in *normal* usage the case 
statement is easier to read because once you see the opening clause you 
know a) that only one of the following cases will be executed, and b) 
that control flow will resume after the case construct.

So despite my nitpicking I do agree with you that there's a margin of 
readability that it might be useful to include in Python to avoid the 
sometimes-lengthy if-elif-elif-elif-elif-elif strings one sometimes sees 
- particularly so if any of the cases require conditionals, as nested 
conditionals are probably among the more difficult sequences to read.

> This is much like saying that a short function is easier to read than a 
> long one.  The long one can obviously do much more, so it's an apples 
> and oranges comparison in that sense.  But clearly if the short one fits 
> all on one screen and the long one does not, the short one is basically 
> much easier to grok.
> 
> That's all I'm saying.
> 
And I'm agreeing.
> 
>>In my experience I've also seen where case statements promote overly long and 
>>partially repetitive code blocks, which would be better constructed in a 
>>top-down fashion.  Admittedly, if statements could be used in a similar way 
>>but I've not seen the same level of abuse with such.  
> 
> 
> That's true.
> 
Indeed any language can be abused, but Python is more concerned with 
making it easy to write good programs than difficult to write bad ones.

> 
>>So arguably, if the translation is pretty much one to one then the argument 
>>is mute :~)  
> 
>    "moot"
> 
Well, if the argument never said anything perhaps it *was* mute too? :-)

> Sort of, except my point here would be that a case statement is then the 
> better choice in many cases because it communicates to the reader that 
> the entire thing *is* simple, while the if/else/if/else does not.
> 
> -Peter

Precisely.

regards
  Steve
-- 
Steve Holden+1 703 861 4237  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-12 Thread Peter Hansen
Chinook wrote:
> On Sun, 12 Jun 2005 17:19:06 -0400, Peter Hansen wrote:
>>Case statements are actually more suitable in many cases even when 
>>performance is not a goal for reasons of *readability*.
>>
>>When reading an if statement, you have to scan down through effective 
>>each statement attempting to find the case in which you are interested. 
>>  Some cases can be compound.  The nested ifs can get confused with the 
>>surrounding ones (in Python or a language with explicit block 
>>delimiters).  The cases are often not written in any particular order, 
>>or they are ordered *for* performance reasons, but in ways that make it 
>>harder to "scan".
> 
> The problem I do see is your apples and oranges argument.  You are equating 
> at the extreme, "compound" if conditions with "_simple_" case statement 
> conditionals.  Yet you are leaving out of your argument the transition from 
> the former to the latter.  If mapping one to the other is simple then the 
> readability is no harder with if statements.  

I dispute that, and believe you've misunderstood my core point.  It's 
not anything to do with "equivalence" between the two approaches.  It's 
that if you see a set of if/else statements, you have to look at all of 
them to understand completely what's happening.  (I mean the structure 
of the if/else... the conditionals, not the contents of the blocks.) 
With a case statement, on the other hand, you *know* that it must be 
just simple conditionals (a series of x == some_constant tests), so you 
don't need to look at all the cases, just the one that interests you.

So it's not a comparison between two ways of writing the same thing, 
it's about the fact that with a case statement there are many things you 
*cannot* write, so reading one is much easier than reading a similarly 
sized compound if/else.

This is much like saying that a short function is easier to read than a 
long one.  The long one can obviously do much more, so it's an apples 
and oranges comparison in that sense.  But clearly if the short one fits 
all on one screen and the long one does not, the short one is basically 
much easier to grok.

That's all I'm saying.

> In my experience I've also seen where case statements promote overly long and 
> partially repetitive code blocks, which would be better constructed in a 
> top-down fashion.  Admittedly, if statements could be used in a similar way 
> but I've not seen the same level of abuse with such.  

That's true.

> So arguably, if the translation is pretty much one to one then the argument 
> is mute :~)  
   "moot"

Sort of, except my point here would be that a case statement is then the 
better choice in many cases because it communicates to the reader that 
the entire thing *is* simple, while the if/else/if/else does not.

-Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-12 Thread Raymond Hettinger
[Joe Stevenson]
> > I skimmed through the docs for Python, and I did not find anything like
> > a case or switch statement.  I assume there is one and that I just
> > missed it.

[deelan]
> topic already beated to death

It's not dead yet.  It has excellent use cases and an open PEP,
http://www.python.org/peps/pep-0275.html .

It needs advocacy, TLC, a clear proposal, an implementer, and a little
luck.


Raymond Hettinger

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-12 Thread Chinook
On Sun, 12 Jun 2005 17:19:06 -0400, Peter Hansen wrote
(in article <[EMAIL PROTECTED]>):

> Steven D'Aprano wrote:
>> On Sat, 11 Jun 2005 19:47:58 -0500, Skip Montanaro wrote:
>>> If the case values are constants known to the compiler, it can generate 
>>> O(1)
>>> code to take the correct branch.
>>> It is precisely this behavior that is desired in many situations.  
>> 
>> Agreed. I certainly don't object to sensible optimizations! But the number
>> of if...elif statements which can be optimised are a vanishingly small
>> subset of the number of possible if...elif statements.
>> 
>> And you can bet your last dollar that many people will use case statements
>> even when doing so gives no advantage, in a mistaken opinion that it will
>> be somehow magically faster.
> 
> Case statements are actually more suitable in many cases even when 
> performance is not a goal for reasons of *readability*.
> 
> When reading an if statement, you have to scan down through effective 
> each statement attempting to find the case in which you are interested. 
>   Some cases can be compound.  The nested ifs can get confused with the 
> surrounding ones (in Python or a language with explicit block 
> delimiters).  The cases are often not written in any particular order, 
> or they are ordered *for* performance reasons, but in ways that make it 
> harder to "scan".
> 
> A case statement, on the other hand, can be a message from the 
> programmer, saying in effect "here's code that represents a series of 
> _simple_ conditionals, ordered (usually) in a sensible way (e.g. 
> ascending numerical order), so just jump to the case you want and carry 
> on maintaining this nice code."
> 
> In current Python the equivalent approach is, of course, a dictionary of 
> some kind, though it's arguable whether this is as clean in many cases 
> as a case statement would be.
> 
> -Peter
> 

I'm new to Python, but I'm retired from a software engineering career that 
began in the early 60s.  I'm not against case statements in the simplest 
syntactical context, but over the years I've seen so many abuses of such 
(i.e. difficult to follow code) that neither am I against their exclusion 
from Python.  The thought being (in my mind) that such might force the 
programmer to rethink their approach to something more intuitively structured 
(whether module/function wise or OO wise or some combination), though I admit 
it is an idealistic view.  

The problem I do see is your apples and oranges argument.  You are equating 
at the extreme, "compound" if conditions with "_simple_" case statement 
conditionals.  Yet you are leaving out of your argument the transition from 
the former to the latter.  If mapping one to the other is simple then the 
readability is no harder with if statements.  An example might be in dealing 
with variably formated records where each record contains a record type flag. 
 On the other hand if you were to map compound conditions to "_simple_" case 
statement conditionals, you need an intermediate translation that must be 
studied to understand the "_simple_" conditionals anyway.  Such translations 
also promote an overabundance of status/flag variables to understand and 
follow which does not increase the readability of code.  

In my experience I've also seen where case statements promote overly long and 
partially repetitive code blocks, which would be better constructed in a 
top-down fashion.  Admittedly, if statements could be used in a similar way 
but I've not seen the same level of abuse with such.  

So arguably, if the translation is pretty much one to one then the argument 
is mute :~)  If on the other hand the translation is many to one, then one's 
skill in developing well structured readable code is really the issue, and 
again case statements are a mute point.  

Lee C


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-12 Thread Peter Hansen
Steven D'Aprano wrote:
> On Sat, 11 Jun 2005 19:47:58 -0500, Skip Montanaro wrote:
>>If the case values are constants known to the compiler, it can generate O(1)
>>code to take the correct branch.
>>It is precisely this behavior that is desired in many situations.  
> 
> Agreed. I certainly don't object to sensible optimizations! But the number
> of if...elif statements which can be optimised are a vanishingly small
> subset of the number of possible if...elif statements.
> 
> And you can bet your last dollar that many people will use case statements
> even when doing so gives no advantage, in a mistaken opinion that it will
> be somehow magically faster.

Case statements are actually more suitable in many cases even when 
performance is not a goal for reasons of *readability*.

When reading an if statement, you have to scan down through effective 
each statement attempting to find the case in which you are interested. 
  Some cases can be compound.  The nested ifs can get confused with the 
surrounding ones (in Python or a language with explicit block 
delimiters).  The cases are often not written in any particular order, 
or they are ordered *for* performance reasons, but in ways that make it 
harder to "scan".

A case statement, on the other hand, can be a message from the 
programmer, saying in effect "here's code that represents a series of 
_simple_ conditionals, ordered (usually) in a sensible way (e.g. 
ascending numerical order), so just jump to the case you want and carry 
on maintaining this nice code."

In current Python the equivalent approach is, of course, a dictionary of 
some kind, though it's arguable whether this is as clean in many cases 
as a case statement would be.

-Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-12 Thread Steven D'Aprano
On Sun, 12 Jun 2005 08:33:32 -0400, Dan Sommers wrote:

>> I've never understood why something like:
> 
>> if x = 5:
>> do_this
>> elif x = 6:
>> do_that
>> else:
>> do_something_else
> 
>> is supposed to be "bad", but
> 
>> case of:
>> x = 5:
>> do_this
>> x = 6:
>> do_that
>> otherwise:
>> do_something_else
> 
>> is supposed to be "good".
> 
> In the truly general case, I agree.
> 
> But twist your second example slightly into this:
> 
> case x of:
> 5: do_this
> 6: do_that
> otherwise: do_something_else
> 
> and the goodness is obvious:  we're choosing functionality based on the
> value of x, so it's nice to see x in only one place.

Yes. But now change the references to do_this and do_that to ten lines
of in-line code each, and add another dozen similar tests for 7, 8, etc,
and by the time you get to the third page you've forgotten what the
variable being tested is.

Now, you or I will obviously never write such hard-to-maintain code
, but some people will, and we'll have to maintain it.

It isn't at all obvious that case statements are more readable than
if...elif, nor are they necessarily faster at runtime, although they can
be. Against that occasional optimization and sometimes increase in
readability, you have disadvantages: more keywords, implicit tests instead
of explicit, new syntax to learn.



>> Arguably, a case statement *might* allow the compiler to optimize the
>> code, maybe, sometimes. But in general, no such optimization is
>> possible, so a case statement is merely equivalent to a series of
>> if...elif...  statements.
> 
> I agree that in general, optimizing a series of if/elif statements is
> tricky, but your first example is very command and exactly the kind of
> code that a good optimizer *can* optimize (as long as "x" isn't
> pathological in the sense that evaluating it also changes its value or
> has other side effects).

Yes. But that's also the sort of optimization that could be done for
if...elif as well, without introducing new syntax and new reserved words.

Case statements seem to be one of those things that Python newbies from
other languages automatically ask for, but the case for introducing case
(pun intended) doesn't appear to be strong enough to justify the amount of
verbiage spent on it.

And on that note, I will say no more on the subject.


-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-12 Thread Dan Sommers
On Sun, 12 Jun 2005 10:35:42 +1000,
Steven D'Aprano <[EMAIL PROTECTED]> wrote:

> I don't relish the idea of especially long case statements.

> I've never understood why something like:

> if x = 5:
> do_this
> elif x = 6:
> do_that
> else:
> do_something_else

> is supposed to be "bad", but

> case of:
> x = 5:
> do_this
> x = 6:
> do_that
> otherwise:
> do_something_else

> is supposed to be "good".

In the truly general case, I agree.

But twist your second example slightly into this:

case x of:
5: do_this
6: do_that
otherwise: do_something_else

and the goodness is obvious:  we're choosing functionality based on the
value of x, so it's nice to see x in only one place.

> Arguably, a case statement *might* allow the compiler to optimize the
> code, maybe, sometimes. But in general, no such optimization is
> possible, so a case statement is merely equivalent to a series of
> if...elif...  statements.

I agree that in general, optimizing a series of if/elif statements is
tricky, but your first example is very command and exactly the kind of
code that a good optimizer *can* optimize (as long as "x" isn't
pathological in the sense that evaluating it also changes its value or
has other side effects).

> There is no case statement in Python. If you don't care about
> readability, one alternative is to use a dictionary:

> case = {5: do_this, 6: do_that}
> case.get(x, do_something_else)()

I find this very readable.  YMMV.

I also find this easier to extend in the "case" (pardon the pun) that my
program expands and x might now be 7 or 8 (or "foo" or 3j).

The biggest drawback here, as others have noted in previous discussions,
is that the do_* functions execute in a separate scope.

Regards,
Dan

-- 
Dan Sommers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-12 Thread invalidemail
Philippe C. Martin wrote:
> Leif K-Brooks wrote:
>
> > Joe Stevenson wrote:
> >> I skimmed through the docs for Python, and I did not find anything like
> >> a case or switch statement.  I assume there is one and that I just
> >> missed it.  Can someone please point me to the appropriate document, or
> >> post an example?  I don't relish the idea especially long if-else
> >> statements.
> >
> > If you really want one, you could use
> > <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410692>.
>
> I _love_ Python!


Well, if you loved that, here's something even more evil.  This was
Bengt Richter's original idea that Cliff Wells and I improved upon.
First define some functions and classes:

. _cache = {}
.
. class _BaseCaseException(Exception):
. pass
.
. def switch(v):
. if v not in _cache:
. class _CaseException(_BaseCaseException):
. pass
. _cache[v] = _CaseException
. raise _cache[v]
.
. def case(v):
. if v not in _cache:
. class _CaseException(_BaseCaseException):
. pass
. _cache[v] = _CaseException
. return _cache[v]
.
. default = _BaseCaseException


Then you can define a switch statement like this:

. x = 2
.
. try: switch(x)
.
. except case(1):
. print "Case 1"
.
. except case(2):
. print "Case 2"
.
. except case(3):
. print "Case 3"
.
. except default:
. print "Default"
.
. except NameError:
. print "You can still catch regular exceptions like NameError"



I-love-Python-too-but-this-isn't-why-ly yr's,

-- 
CARL BANKS

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-12 Thread Steven D'Aprano
On Sat, 11 Jun 2005 19:47:58 -0500, Skip Montanaro wrote:

> If the case values are constants known to the compiler, it can generate O(1)
> code to take the correct branch.  (In fact, that could be done by the
> compiler for if statements such as in your example today.  It just isn't.)
> It is precisely this behavior that is desired in many situations.  See PEP
> 275 for details:

Agreed. I certainly don't object to sensible optimizations! But the number
of if...elif statements which can be optimised are a vanishingly small
subset of the number of possible if...elif statements.

And you can bet your last dollar that many people will use case statements
even when doing so gives no advantage, in a mistaken opinion that it will
be somehow magically faster.

In fact, some languages even encourage this: I recall the old 4GL (back in
the early 1990s when developers actually used the term Fourth Generation
Language unselfconsciously) used to develop the spreadsheet "Wingz". It
included two different forms for case. By memory:

case EXPR of:
VALUE:
SUITE
VALUE:
SUITE
otherwise:
SUITE

(which could potentially be optimised) and a second form:

case:
EXPR of:
SUITE
EXPR of:
SUITE
otherwise:
SUITE

which was almost certainly nothing more than syntactic sugar for:

if EXPR then:
SUITE
else if EXPR then:
SUITE
else:
SUITE

In any case, even when case statements can be optimized (and we all know
the lesson about premature optimization), the original poster's complaint
appeared to be purely a stylistic issue: he didn't relish using long
if..elif statements. Who does? Not I. My comment, I hope, will remind
folks that long pieces of branching code are ugly regardless of which
syntax you use.


-- 
Steven.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-11 Thread Terry Hancock
On Saturday 11 June 2005 07:35 pm, Steven D'Aprano wrote:
> On Sat, 11 Jun 2005 16:15:42 +, Joe Stevenson wrote:
> > I skimmed through the docs for Python, and I did not find anything like 
> > a case or switch statement.  I assume there is one and that I just 
> > missed it.  Can someone please point me to the appropriate document, or 
> > post an example?  I don't relish the idea especially long if-else 
> > statements.
> 
[...]
> There is no case statement in Python. If you don't care about
> readability, one alternative is to use a dictionary:
> 
> case = {5: do_this, 6: do_that}
> case.get(x, do_something_else)()

The really nice thing about using dictionaries for this kind of thing
in Python is that what was previously hardcoded is now (dynamic)
data.  That makes alterations like adding a new case extremely
trivial (you could load it from a config file for example, or it could
be altered by plugin code which simply updates the dictionary to
register itself).  In my experience with C, this kind of change always
comes up with switch statements, so it's nice to neatly sidestep
the problem with dictionaries in Python.

And perhaps that removal of a false lead is the real reason Python
doesn't have a switch/case construct -- it encourages you to
use a smarter solution which you'll be glad of later on.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-11 Thread Skip Montanaro

Steven> I've never understood why something like:

Steven> if x = 5:
Steven> do_this
Steven> elif x = 6:
Steven> do_that
Steven> else:
Steven> do_something_else

Steven> is supposed to be "bad", but

Steven> case of:
Steven> x = 5:
Steven> do_this
Steven> x = 6:
Steven> do_that
Steven> otherwise:
Steven> do_something_else

Steven> is supposed to be "good".

...

Steven> Arguably, a case statement *might* allow the compiler to
Steven> optimize the code, maybe, sometimes. 

If the case values are constants known to the compiler, it can generate O(1)
code to take the correct branch.  (In fact, that could be done by the
compiler for if statements such as in your example today.  It just isn't.)
It is precisely this behavior that is desired in many situations.  See PEP
275 for details:

http://www.python.org/peps/pep-0275.html

Skip
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-11 Thread Steven D'Aprano
On Sat, 11 Jun 2005 16:15:42 +, Joe Stevenson wrote:

> Hi all,
> 
> I skimmed through the docs for Python, and I did not find anything like 
> a case or switch statement.  I assume there is one and that I just 
> missed it.  Can someone please point me to the appropriate document, or 
> post an example?  I don't relish the idea especially long if-else 
> statements.

I don't relish the idea of especially long case statements.

I've never understood why something like:

if x = 5:
do_this
elif x = 6:
do_that
else:
do_something_else

is supposed to be "bad", but

case of:
x = 5:
do_this
x = 6:
do_that
otherwise:
do_something_else

is supposed to be "good".

(Choose whatever syntax you prefer for case statements, the principle
remains.)

Arguably, a case statement *might* allow the compiler to optimize the
code, maybe, sometimes. But in general, no such optimization is possible,
so a case statement is merely equivalent to a series of if...elif...
statements.

There is no case statement in Python. If you don't care about
readability, one alternative is to use a dictionary:

case = {5: do_this, 6: do_that}
case.get(x, do_something_else)()



-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-11 Thread Philippe C. Martin
I _love_ Python!


Leif K-Brooks wrote:

> Joe Stevenson wrote:
>> I skimmed through the docs for Python, and I did not find anything like
>> a case or switch statement.  I assume there is one and that I just
>> missed it.  Can someone please point me to the appropriate document, or
>> post an example?  I don't relish the idea especially long if-else
>> statements.
> 
> If you really want one, you could use
> <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410692>.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-11 Thread Leif K-Brooks
Joe Stevenson wrote:
> I skimmed through the docs for Python, and I did not find anything like 
> a case or switch statement.  I assume there is one and that I just 
> missed it.  Can someone please point me to the appropriate document, or 
> post an example?  I don't relish the idea especially long if-else 
> statements.

If you really want one, you could use
<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410692>.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-11 Thread deelan
Joe Stevenson wrote:
> Hi all,
> 
> I skimmed through the docs for Python, and I did not find anything like 
> a case or switch statement.  I assume there is one and that I just 
> missed it.  

strictly speaking, python does not
have a switch stamenent.

"Why isn't there a switch or case statement in Python?"
<http://www.python.org/doc/faq/general.html#why-isn-t-there-a-switch-or-case-statement-in-python>

> Can someone please point me to the appropriate document, or 
> post an example?  I don't relish the idea especially long if-else 
> statements.

topic already beated to death, feel
free to browse the group archives:
<http://groups-beta.google.com/groups?q=comp.lang.python+switch+statement>

HTH.

-- 
deelan <http://www.deelan.com>
-- 
http://mail.python.org/mailman/listinfo/python-list


case/switch statement?

2005-06-11 Thread Joe Stevenson
Hi all,

I skimmed through the docs for Python, and I did not find anything like 
a case or switch statement.  I assume there is one and that I just 
missed it.  Can someone please point me to the appropriate document, or 
post an example?  I don't relish the idea especially long if-else 
statements.

Joe



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Pseudo-Switch

2005-05-09 Thread Jason Mobarak
# -*- python -*-

import sys


def switchFor (target):
sw = '__switch_table__'
# please pretend the frame hack is not here,
# it happens to work for classes and messing with
# frame stack in a try/except is probably okay
try:
raise Exception()
except:
defs = sys.exc_info()[2].tb_frame.f_back.f_locals
if sw not in defs:
defs[sw] = {}
table = defs[sw]
def _(meth):
table[target] = meth
return meth
return _


class SwitchMixin (object):

def __init__ (self):
self.__switch_table__ = self.__switch_table__.copy()

def switchOn (self, target, *args, **kw):
return self.__switch_table__[target](self, *args, **kw)


if __name__ == '__main__':

class SwitchTest(SwitchMixin):

@switchFor("foo")
def switch (self, arg):
print arg * 3

@switchFor("bar")
def switch (self, arg):
print "__%s__" % (arg,)

@switchFor("baz")
def switch (self, arg):
print arg + ''.join(reversed(arg))

st = SwitchTest()

st.switchOn("foo", "oof")
st.switchOn("bar", "rab")
st.switchOn("baz", "zab")

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Pseudo-Switch

2005-05-07 Thread Jason Mobarak
James Stroud wrote:
> Hello All,
>
> Because of my poorly designing a database, I have recently found it
necessary
> to explore the wonders of the Python pseudo-switch:
>
> do_case = { "A" : lambda x: x["bob"],
> "B" : lambda x: x["carol"],
> "C" : lambda x: "Ted",
> "D" : lambda x: do_something(x) }
>

class CaseThing:
  def pref_A (self, x):
return x["bob"]
  def pref_B (self, x):
return x["carol"]
  def pref_C (self, x);
return "Ted"
  def pref_D (self, x)
return do_something(x)
  def getThing (self, x):
attr = getattr(self, 'pref_%s' % (x,))
if attr is not None:
  return attr
else:
  raise SomeError("Thing %s does not exist" % (x,))

my_thing = CaseThing().getThing(get_value_from_thin_air)(adict)

You can do something similar with method decorators for more complex
strings than what's allowed for python method names.

> my_thing = do_case[get_value_from_thin_air()](adict)
>
>
> How to handle this kind of thing when lambda is removed from the
language,
> beside the obvious def'ing those tiny little functions?
>
> James
>
> --
> James Stroud
> UCLA-DOE Institute for Genomics and Proteomics
> Box 951570
> Los Angeles, CA 90095
> 
> http://www.jamesstroud.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Pseudo-Switch

2005-05-07 Thread Dan Bishop
James Stroud wrote:
> Hello All,
>
> Because of my poorly designing a database, I have recently found it
necessary
> to explore the wonders of the Python pseudo-switch:
>
> do_case = { "A" : lambda x: x["bob"],
> "B" : lambda x: x["carol"],
> "C" : lambda x: "Ted",
> "D" : lambda x: do_something(x) }
>
> my_thing = do_case[get_value_from_thin_air()](adict)
>
>
> How to handle this kind of thing when lambda is removed from the
language,
> beside the obvious def'ing those tiny little functions?

You can always re-invent lambda.

>>> def lambda2(arg_names, expression):
...exec 'def _(%s): return %s' % (','.join(arg_names), expression)
...return _
...
>>> add = lambda2(('x', 'y'), 'x + y')
>>> add(3, 4)
7

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Pseudo-Switch

2005-05-07 Thread Terry Reedy

"James Stroud" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Because of my poorly designing a database, I have recently found it 
> necessary
> to explore the wonders of the Python pseudo-switch:
>
> do_case = { "A" : lambda x: x["bob"],
>"B" : lambda x: x["carol"],
>"C" : lambda x: "Ted",
>"D" : lambda x: do_something(x) }
>
> my_thing = do_case[get_value_from_thin_air()](adict)
>
> How to handle this kind of thing when lambda is removed from the 
> language,
> beside the obvious def'ing those tiny little functions?

I don't believe any cast-in-concrete decision about lambda has been made 
yet.  I expect there will be a PEP for removals when appropriate.  Comments 
such as this will bolster the case against removal without replacement if 
then resubmitted

TJR




-- 
http://mail.python.org/mailman/listinfo/python-list


Python Pseudo-Switch

2005-05-07 Thread James Stroud
Hello All,

Because of my poorly designing a database, I have recently found it necessary 
to explore the wonders of the Python pseudo-switch:

do_case = { "A" : lambda x: x["bob"],
"B" : lambda x: x["carol"],
"C" : lambda x: "Ted",
"D" : lambda x: do_something(x) }

my_thing = do_case[get_value_from_thin_air()](adict)


How to handle this kind of thing when lambda is removed from the language, 
beside the obvious def'ing those tiny little functions?

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple, elegant, pythonic solution for switch statement

2005-04-26 Thread bruno modulix
python_only wrote:
Check it out!
Readable switch construction without lambdas or dictionaries:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410692
Not sure I'll have a need for it, but, yes, nice job !-)
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for 
p in '[EMAIL PROTECTED]'.split('@')])"
--
http://mail.python.org/mailman/listinfo/python-list


Simple, elegant, pythonic solution for switch statement

2005-04-26 Thread python_only
Check it out!

Readable switch construction without lambdas or dictionaries:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410692

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Switch statement (was: Lambda going out of fashion)

2005-01-03 Thread TZOTZIOY
On Thu, 23 Dec 2004 19:57:27 GMT, rumours say that rzed
<[EMAIL PROTECTED]> might have written:

[Why did PEP 275 stall?]

>It seems to me that it was regarded as misguidod.

QOTPE +1

(PE=Python Era)

Oncoming Python book: "Hitchhiker's Guido to the Python Language"
-- 
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Switch statement (was: Lambda going out of fashion)

2004-12-23 Thread rzed
Skip Montanaro <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> 
> Stephen> {
> Stephen>  'one': lambda x:x.blat(),
> Stephen>  'two': lambda x:x.blah(),
> Stephen> }.get(someValue, lambda x:0)(someOtherValue)
> 
> One thing to remember is that function calls in Python are
> pretty damn expensive.  If x.blat() or x.blah() are themselves
> only one or two lines of code, you might find that your "switch"
> statement is better written as an if/elif/else statement. 
> You're making potentially three function calls (get(), lambda
> and x.blat() or x.blah()) to perform what might only be a small
> handful of inline statements.  I'll ignore the readability cost
> of your solution vs. an if statement.
> 
> Stephen> So, the questions I am asking are: Is this okay
> with everyone? 
> 
> Sure.  I'll adjust.
> 
> Stephen> Does anyone else feel that lambda is useful in this
> kind of Stephen> context?
> 
> It's useful in this sort of context.  It will probably always be
> limited to single expressions, which will always leave it a
> second-class citizen in Python.  Interestingly enough, lambda in
> the Lisp world has the same limitation, however, since Lisp code
> is nothing but a series of s-expressions, that's not a problem.
> 
>     Stephen> Are there alternatives I have not considered?
> 
> I've never seen a situation where if/elif/else wasn't adequate
> or was less clear than the many attempts at switch-like
> behavior. 
> 
> Folks (in general), there is still an open PEP on a switch
> statement for Python.  It's been idle since late 2001:
> 
> http://www.python.org/peps/pep-0275.html
> 
> It would help if interested people were to take a look at it and
> identify open issues.  If you google for pep 275 you will
> probably find relevant python-dev discussions from the 2001/2002
> timeframe.  Thomas Wouters' patch for the interpreter would also
> need to be resurrected and brought up-to-date.  I not longer
> remember why the PEP stalled. 
> 

It seems to me that it was regarded as misguidod.

-- 
rzed

-- 
http://mail.python.org/mailman/listinfo/python-list


Switch statement (was: Lambda going out of fashion)

2004-12-23 Thread Skip Montanaro

Stephen> {
Stephen>  'one': lambda x:x.blat(),
Stephen>  'two': lambda x:x.blah(),
Stephen> }.get(someValue, lambda x:0)(someOtherValue)

One thing to remember is that function calls in Python are pretty damn
expensive.  If x.blat() or x.blah() are themselves only one or two lines of
code, you might find that your "switch" statement is better written as an
if/elif/else statement.  You're making potentially three function calls
(get(), lambda and x.blat() or x.blah()) to perform what might only be a
small handful of inline statements.  I'll ignore the readability cost of
your solution vs. an if statement.

Stephen> So, the questions I am asking are: Is this okay with everyone?

Sure.  I'll adjust.

Stephen> Does anyone else feel that lambda is useful in this kind of
Stephen> context?

It's useful in this sort of context.  It will probably always be limited to
single expressions, which will always leave it a second-class citizen in
Python.  Interestingly enough, lambda in the Lisp world has the same
limitation, however, since Lisp code is nothing but a series of
s-expressions, that's not a problem.

Stephen> Are there alternatives I have not considered?

I've never seen a situation where if/elif/else wasn't adequate or was less
clear than the many attempts at switch-like behavior.

Folks (in general), there is still an open PEP on a switch statement for
Python.  It's been idle since late 2001:

http://www.python.org/peps/pep-0275.html

It would help if interested people were to take a look at it and identify
open issues.  If you google for pep 275 you will probably find relevant
python-dev discussions from the 2001/2002 timeframe.  Thomas Wouters' patch
for the interpreter would also need to be resurrected and brought
up-to-date.  I not longer remember why the PEP stalled.

Skip
-- 
http://mail.python.org/mailman/listinfo/python-list


<    1   2   3   4