On 14/03/2016 23:24, Steven D'Aprano wrote:
On Mon, 14 Mar 2016 06:39 am, BartC wrote:

class switch(object):
      value = None
      def __new__(class_, value):
          class_.value = value
          return True

def case(*args):
      return any((arg == switch.value for arg in args))

That's quite a clever use of a class. By clever, I mean imaginative, not
necessarily smart.

I think so too. But it also looks inefficient.

Try this instead:

c = chr(c)
if 'A' <= c <= 'Z':
     upper += 1
elif 'a' <= c <= 'z':
     lower += 1
elif '0' <= c <= '9':
     digits += 1
else:
     other += 1


But even better:

if c.isupper():
     upper += 1
elif c islower():
     lower += 1
elif c.isdigit():
     digits += 1
else:
     other += 1


which will work correctly for non-ASCII characters as well.

Yes, but now you've destroyed my example!

A more realistic use of switch is shown below [not Python]. I've taken out the code for each section, including various nested switches, to show the test patterns better.

Now an if-elif chain won't perform as well.


doswitch p++^           # (looping switch)
when 'a'..'z','$','_' then
when '0'..'9' then
when 'A'..'Z' then
when '!' then
when '#' then
when '\\' then
when '{' then
when '}' then
when '.' then
when ',' then
when ';' then
when ':' then
when '(' then
when ')' then
when '[' then
when ']' then
when '|' then
when '^' then
when '@' then
when '?' then
when '£' then
when '~' then
when '¬' then
when '+' then
when '-' then
when '*' then
when '/' then
when '%' then
when '=' then
when '<' then
when '>' then
when '&' then
when '\'','`' then
when '"' then
when ' ','\t' then
when cr then
when lf then
when etx,0 then
else            # unicode goes here...
end switch

--
Bartc
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to