Re: [Python-Dev] Re: switch statement

2005-04-28 Thread Stephen J. Turnbull
 Guido == Guido van Rossum [EMAIL PROTECTED] writes:

Guido You mean like this?

if x  0:
...normal case...
elif y  0:
abnormal case...
else:
...edge case...

The salient example!  If it's no accident that those conditions are
mutually exclusive and exhaustive, doesn't that code require at least
a comment saying so, and maybe even an assertion to that effect?
Where you can use a switch, it gives both, and throws in economy in
both source and object code as a bonus.

Not a compelling argument---your example shows switches are not
universally applicable---but it's a pretty good deal.

Guido You have guts to call that bad style! :-)

Exaggeration in defense of elegance is no vice.wink

-- 
School of Systems and Information Engineering http://turnbull.sk.tsukuba.ac.jp
University of TsukubaTennodai 1-1-1 Tsukuba 305-8573 JAPAN
   Ask not how you can do free software business;
  ask what your business can do for free software.
___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Re: switch statement

2005-04-28 Thread Guido van Rossum
 Exaggeration in defense of elegance is no vice.wink

Maybe not, but it still sounds like BS to me.

-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)
___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Re: switch statement

2005-04-28 Thread Michael Walter
On 4/28/05, Stephen J. Turnbull [EMAIL PROTECTED] wrote:
  Guido == Guido van Rossum [EMAIL PROTECTED] writes:
 
 Guido You mean like this?
 
 if x  0:
 ...normal case...
 elif y  0:
 abnormal case...
 else:
 ...edge case...
 
 The salient example!  If it's no accident that those conditions are
 mutually exclusive and exhaustive, doesn't that code require at least
 a comment saying so, and maybe even an assertion to that effect?

I usually do:

if ...:
  return ...
if ...:
  return ...
assert ...
return ...

Michael
___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


RE: [Python-Dev] Re: switch statement

2005-04-27 Thread Michael Chermside
Guido writes:
 You mean like this?

 if x  0:
...normal case...
 elif y  0:
 abnormal case...
 else:
 ...edge case...

 You have guts to call that bad style! :-)

Well, maybe, but this:

if x == 1:
   do_number_1()
elif x == 2:
   do_number_2()
elif x == 3:
   do_number_3()
elif y == 4:
   do_number_4()
elif x == 5:
   do_number_5()
else:
   raise ValueError

is clearly bad style. (Even knowing what I did here, how long does it
take you to find the problem? Hint: line 7.)

I've seen Jim's recipe in the cookbook, and as I said there, I'm impressed
by the clever implementation, but I think it's unwise. PEP 275 proposes
an O(1) solution... either by compiler optimization of certain
if-elif-else structures, or via a new syntax with 'switch' and 'case'
keywords. (I prefer the keywords version myself... that optimization
seems awefully messy, and wouldn't help with the problem above.) Jim's
recipe fixes the problem given above, but it's a O(n) solution, and to
me the words 'switch' and 'case' just *scream* O(1). But perhaps
it's worthwhile, just because it avoids repeating x ==.

Really, this seems like a direct analog of another frequently-heard
Python gripe: the lack of a conditional expression. After all, the
problems with these two code snippets:

 if x == 1:|if condition_1:
do_1() |y = 1
 elif x == 2:  |elif condition_2:
do_2() |y = 2
 elif x == 3:  |elif condition_3:
do_3() |y = 3
 else: |else:
default()  |y = 4

is the repetition of x == and of y =. As my earlier example
demonstrates, a structure like this in which the x == or the
y = VARIES has a totally different *meaning* to the programmer
than one in which the x == or y = is the same for every
single branch.

But let's not start discussing conditional expressions now,
because there's already more traffic on the list than I can read.

-- Michael Chermside

___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Re: switch statement

2005-04-27 Thread Shane Hathaway
Michael Chermside wrote:
  if x == 1:|if condition_1:
 do_1() |y = 1
  elif x == 2:  |elif condition_2:
 do_2() |y = 2
  elif x == 3:  |elif condition_3:
 do_3() |y = 3
  else: |else:
 default()  |y = 4

This inspired a twisted thought: if you just redefine truth, you don't
have to repeat the variable. 0.9 wink

True = x
if 1:
do_1()
elif 2:
do_2()
elif 3:
do_3()
else:
default()

Shane
___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Re: switch statement

2005-04-25 Thread M.-A. Lemburg
Shannon -jj Behrens wrote:
 On 4/20/05, M.-A. Lemburg [EMAIL PROTECTED] wrote:
 
Fredrik Lundh wrote:

PS. a side effect of the for-in pattern is that I'm beginning to feel
that Python
might need a nice switch statement based on dictionary lookups, so I can
replace multiple callbacks with a single loop body, without writing too
many
if/elif clauses.

PEP 275 anyone ? (http://www.python.org/peps/pep-0275.html)

My use case for switch is that of a parser switching on tokens.

mxTextTools applications would greatly benefit from being able
to branch on tokens quickly. Currently, there's only callbacks,
dict-to-method branching or long if-elif-elif-...-elif-else.
 
 I think match from Ocaml would be a much nicer addition to Python
 than switch from C.

PEP 275 is about branching based on dictionary lookups which
is somewhat different than pattern matching - for which we
already have lots and lots of different tools.

The motivation behind the switch statement idea is that of
interpreting the multi-state outcome of some analysis that
you perform on data. The main benefit is avoiding Python
function calls which are very slow compared to branching to
inlined Python code.

Having a simple switch statement
would enable writing very fast parsers in Python -
you'd let one of the existing tokenizers such as mxTextTools,
re or one of the xml libs create the token input data
and then work on the result using a switch statement.

Instead of having one function call per token, you'd
only have a single dict lookup.

BTW, has anyone in this thread actually read the PEP 275 ?

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Apr 25 2005)
 Python/Zope Consulting and Support ...http://www.egenix.com/
 mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
 mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! 
___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Re: switch statement

2005-04-25 Thread Donovan Baarda
On Mon, 2005-04-25 at 18:20 -0400, Jim Jewett wrote:
[...]
 If speed for a limited number of cases is the only advantage, 
 then I would say it belongs in (at most) the implementation, 
 rather than the language spec.  

Agreed. I don't find any switch syntaxes better than if/elif/else. Speed
benefits belong in implementation optimisations, not new bad syntax.

-- 
Donovan Baarda [EMAIL PROTECTED]
http://minkirri.apana.org.au/~abo/

___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Re: switch statement

2005-04-25 Thread Donovan Baarda
On Mon, 2005-04-25 at 21:21 -0400, Brian Beck wrote:
 Donovan Baarda wrote:
  Agreed. I don't find any switch syntaxes better than if/elif/else. Speed
  benefits belong in implementation optimisations, not new bad syntax.
 
 I posted this 'switch' recipe to the Cookbook this morning, it saves
 some typing over the if/elif/else construction, and people seemed to
 like it. Take a look:
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410692

Very clever... you have shown that current python syntax is capable of
almost exactly replicating a C case statement.

My only problem is C case statements are ugly. A simple if/elif/else is
much more understandable to me. 

The main benefit in C of case statements is the compiler can optimise
them. This copy of a C case statement will be slower than an
if/elif/else, and just as ugly :-)

-- 
Donovan Baarda [EMAIL PROTECTED]
http://minkirri.apana.org.au/~abo/

___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Re: switch statement

2005-04-25 Thread Greg Ewing
Donovan Baarda wrote:
Agreed. I don't find any switch syntaxes better than if/elif/else. Speed
benefits belong in implementation optimisations, not new bad syntax.
Two things are mildly annoying about if-elif chains as a
substitute for a switch statement:
1) Repeating the name of the thing being switched on all the time,
   and the operator being used for comparison.
2) The first case is syntactically different from subsequent ones,
   even though semantically all the cases are equivalent.
--
Greg Ewing, Computer Science Dept, +--+
University of Canterbury,  | A citizen of NewZealandCorp, a   |
Christchurch, New Zealand  | wholly-owned subsidiary of USA Inc.  |
[EMAIL PROTECTED]  +--+
___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Re: switch statement

2005-04-21 Thread Michael Hudson
Shannon -jj Behrens [EMAIL PROTECTED] writes:

 On 4/20/05, M.-A. Lemburg [EMAIL PROTECTED] wrote:

 My use case for switch is that of a parser switching on tokens.
 
 mxTextTools applications would greatly benefit from being able
 to branch on tokens quickly. Currently, there's only callbacks,
 dict-to-method branching or long if-elif-elif-...-elif-else.

 I think match from Ocaml would be a much nicer addition to Python
 than switch from C.

Can you post a quick summary of how you think this would work?

Cheers,
mwh

-- 
  We did requirements and task analysis, iterative design, and user
  testing. You'd almost think programming languages were an interface
  between people and computers.-- Steven Pemberton
  (one of the designers of Python's direct ancestor ABC)
___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Re: switch statement

2005-04-21 Thread Andrew McGregor
I can post an alternative, inspired by this bit of Haskell (I've  
deliberately left out the Haskell type annotation for this):

zoneOpts argv =
   case getOpt Permute options argv of
  (o,n,[]) - return (o,n)
  (_,_,errs) - error errs
which could, in a future Python, look something like:
def zoneOpts(argv):
case i of getopt(argv, options, longoptions):
i[2]:
raise OptionError(i[2])
True:
return i[:2]
The intent is that within the case, the bit before each : is a boolean  
expression, they're evaluated in order, and the following block is  
executed for the first one that evaluates to be True.  I know we have  
exceptions for this specific example, but it's just an example.  I'm  
also assuming for the time being that getopt returns a 3-tuple  
(options, arguments, errors) like the Haskell version does, just for  
the sake of argument, and there's an OptionError constructor that will  
do something with that error list..

Yes, that is very different semantics from a Haskell case expression,  
but it kind of looks like a related idea.  A more closely related idea  
would be to borrow the Haskell patterns:

def zoneOpts(argv):
case getopt(argv, options, longoptions):
(o,n,[]):
return o,n
(_,_,errs):
raise OptionError(errs)
where _ matches anything, a presently unbound name is bound for the  
following block by mentioning it, a bound name would match whatever  
value it referred to, and a literal matches only itself.  The first  
matching block gets executed.

Come to think of it, it should be possible to do both.
Not knowing Ocaml, I'd have to presume that 'match' is somewhat similar.
Andrew
On 21/04/2005, at 9:30 PM, Michael Hudson wrote:
Shannon -jj Behrens [EMAIL PROTECTED] writes:
On 4/20/05, M.-A. Lemburg [EMAIL PROTECTED] wrote:
My use case for switch is that of a parser switching on tokens.
mxTextTools applications would greatly benefit from being able
to branch on tokens quickly. Currently, there's only callbacks,
dict-to-method branching or long if-elif-elif-...-elif-else.
I think match from Ocaml would be a much nicer addition to Python
than switch from C.
Can you post a quick summary of how you think this would work?
Cheers,
mwh
--  
  We did requirements and task analysis, iterative design, and user
  testing. You'd almost think programming languages were an interface
  between people and computers.-- Steven Pemberton
  (one of the designers of Python's direct ancestor ABC)
___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:  
http://mail.python.org/mailman/options/python-dev/ 
andrew%40indranet.co.nz


___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


RE: [Python-Dev] Re: switch statement

2005-04-21 Thread Michael Chermside
Andrew McGregor writes:
 I can post an alternative, inspired by this bit of Haskell
[...]
 The intent is that within the case, the bit before each : is a boolean
 expression, they're evaluated in order, and the following block is
 executed for the first one that evaluates to be True.

If we're going to be evaluating a series of booleans, then the One Proper
Format in Python is:

 if bool-expr-1:
 suite-1
 elif bool-expr-2:
 suite-2
 elif bool-expr-3:
 suite-3
 else:
 default-suite

When people speak of introducing a switch statement they are speaking
of a construct in which the decision of which branch to take requires
time proportional to something LESS than a linear function of the number
of branches (it's not O(n) in the number of branches).

Now the pattern matching is more interesting, but again, I'd need to
see a proposed syntax for Python before I could begin to consider it.
If I understand it properly, pattern matching in Haskell relies
primarily on Haskell's excellent typing system, which is absent in
Python.

-- Michael Chermside

___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Re: switch statement

2005-04-21 Thread Nick Coghlan
Michael Chermside wrote:
Now the pattern matching is more interesting, but again, I'd need to
see a proposed syntax for Python before I could begin to consider it.
If I understand it properly, pattern matching in Haskell relies
primarily on Haskell's excellent typing system, which is absent in
Python.
There's no real need for special syntax in Python - an appropriate tuple 
subclass will do the trick quite nicely:

class pattern(tuple):
  ignore = object()
  def __new__(cls, *args):
return tuple.__new__(cls, args)
  def __hash__(self):
raise NotImplementedError
  def __eq__(self, other):
if len(self) != len(other):
return False
for item, other_item in zip(self, other):
  if item is pattern.ignore:
continue
  if item != other_item:
return False
return True
Py x = (1, 2, 3)
Py print x == pattern(1, 2, 3)
True
Py print x == pattern(1, pattern.ignore, pattern.ignore)
True
Py print x == pattern(1, pattern.ignore, 3)
True
Py print x == pattern(2, pattern.ignore, pattern.ignore)
False
Py print x == pattern(1)
False
It's not usable in a dict-based switch statement, obviously, but it's perfectly 
compatible with the current if/elif idiom.

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Re: switch statement

2005-04-21 Thread Michael Hudson
Samuele Pedroni [EMAIL PROTECTED] writes:

 Michael Hudson wrote:

[pattern matching]

Can you post a quick summary of how you think this would work?

  
 Well, Python lists are used more imperatively and are not made up
 with cons cells, we have dictionaries which because of ordering
 issues are not trivial to match, and no general ordered records with
 labels.

That's a better way of putting it than pattern matching and python
don't really seem to fit together, for sure :)

(I'd quite like records with labels, tangentially, but am not so wild
about ordering)

 We have objects and not algebraic data types. Literature on the
 topic usually indicates the visitor pattern as the moral equivalent
 of pattern matching in an OO-context vs. algebraic data
 types/functional one. I agree with that point of view and Python has
 idioms for the visitor pattern.

But the visitor pattern is pretty grim, really.  It would be nice (tm)
to have something like:

  match node in:
Assign(lhs=Var(_), rhs=_):
   # lhs, rhs bound in here
Assign(lhs=Subscr(_,_), rhs=_):
   # ditto
Assign(lhs=Slice(*_), rhs=_):
   # ditto
Assign(lhs=_, rhs=_):
   raise SyntaxError
 
in Lib/compiler.

Vyper had something like this, I think.


 Interestingly even in the context of objects one can leverage the
 infrastructure that is there for generalized copying/pickling to
 allow generalized pattern matching of nested object data
 structures. Whether it is practical I don't know.

   class Pt:
 ...   def __init__(self, x,y):
 ... self.x = x
 ... self.y = y
 ...
   p(lambda _: Pt(1, _()) ).match(Pt(1,3))
 (3,)
   p(lambda _: Pt(1, Pt(_(),_(.match(Pt(1,Pt(Pt(5,6),3)))
 (__main__.Pt instance at 0x40200b4c, 3)

 http://codespeak.net/svn/user/pedronis/match.py is an experiment in
 that direction (preceding this discussion
 and inspired while reading a book that was using OCaml for its examples).

Yikes!

 Notice that this is quite grossly subclassing pickling infrastracture
 (the innocent bystander should probably not try that), a cleaner
 approach redoing that logic with matching in mind is possible and
 would be preferable.

Also, the syntax is disgusting.  But that's a separate issue, I guess.

Cheers,
mwh

-- 
  /* I'd just like to take this moment to point out that C has all
 the expressive power of two dixie cups and a string.
   */   -- Jamie Zawinski from the xkeycaps source
___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Re: switch statement

2005-04-21 Thread Phillip J. Eby
At 06:10 PM 04/21/2005 +0100, Michael Hudson wrote:
But the visitor pattern is pretty grim, really.  It would be nice (tm)
to have something like:
  match node in:
Assign(lhs=Var(_), rhs=_):
   # lhs, rhs bound in here
Assign(lhs=Subscr(_,_), rhs=_):
   # ditto
Assign(lhs=Slice(*_), rhs=_):
   # ditto
Assign(lhs=_, rhs=_):
   raise SyntaxError
in Lib/compiler.
FWIW, I do intend to add this sort of thing to PyProtocols' predicate 
dispatch system.  Actually, I can dispatch on rules like the above now, 
it's just that you have to spell out the cases as e.g.:

@do_it.when(isinstance(node, Assign) and isinstance(node.lhs, Subscr))
def do_subscript_assign(node, ...):
...
I'd like to create a syntax sugar for pattern matching though, that would 
let you 1) use a less verbose way of saying the same thing, and 2) let you 
bind the intermediate values to variables that then become accessible in 
the function body as locals.

Anyway, the main holdup on this is deciding what sort of Python syntax 
abuse should represent variable bindings.  :)  Maybe something like this 
will be suitably horrific:

   @do_it.when(node in Assign.match(lhs=`lhs` in Subscr,rhs=`rhs`))
   def do_subscript_assign((lhs,rhs), node, ...):
   ...
But I think maybe here the cure is worse than the disease.  :)  Pushed this 
far, it seems to beg for new syntax to accommodate in-expression variable 
bindings, something like 'var:=value'.  Really, though, the problem is 
probably just that inline variable binding is downright unpythonic.  The 
only time Python does anything vaguely similar is with the 'except 
type,var:' syntax.

___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com


Re: [Python-Dev] Re: switch statement

2005-04-20 Thread Shannon -jj Behrens
On 4/20/05, M.-A. Lemburg [EMAIL PROTECTED] wrote:
 Fredrik Lundh wrote:
  PS. a side effect of the for-in pattern is that I'm beginning to feel
  that Python
  might need a nice switch statement based on dictionary lookups, so I can
  replace multiple callbacks with a single loop body, without writing too
  many
  if/elif clauses.
 
 PEP 275 anyone ? (http://www.python.org/peps/pep-0275.html)
 
 My use case for switch is that of a parser switching on tokens.
 
 mxTextTools applications would greatly benefit from being able
 to branch on tokens quickly. Currently, there's only callbacks,
 dict-to-method branching or long if-elif-elif-...-elif-else.

I think match from Ocaml would be a much nicer addition to Python
than switch from C.

-jj

-- 
I have decided to switch to Gmail, but messages to my Yahoo account will
still get through.
___
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com