Design Patterns / Idioms

A forum for general discussion of the Python programming language.

Design Patterns / Idioms

Postby lseki » Tue Dec 10, 2013 12:41 am

Hi there.

I have a quite abstract question:

In Python, the 'in' statement like this:
Code: Select all
if 1 in [ 1, 2, 3 ]:
  print "1 is in the list"


Is equivalent to:
Code: Select all
if [1, 2, 3].__contains__(1):
  print "1 is in the list"


In Groovy, the switch-case statement calls the isCase method from the matchables, passing switchValue as argument. So,
Code: Select all
switch( switchValue ) {
  case Number:
    printf( "switchValue is a Number")
  case 'a':
    printf( "switchValue is 'a'")
}


is equivalent to

Code: Select all
if ( Number.isCase(switchValue) ) {
  printf( "switchValue is a Number")
}
if ( "a".isCase(switchValue) ) {
  printf("switchValue is a")
}


I found that these two implementations are similar in reversing the order of the object calling the method, and its argument.

Is it a kind of design pattern or idiom, well known by the language developers?
If so, are there any other cool patterns like these?

Cheers,
Last edited by micseydel on Tue Dec 10, 2013 3:16 am, edited 1 time in total.
Reason: Code tags, first post lock.
lseki
 
Posts: 2
Joined: Tue Dec 10, 2013 12:37 am

Re: Design Patterns / Idioms

Postby ochichinyezaboombwa » Tue Dec 10, 2013 6:30 am

I have no idea about Groovy but I BET that
Code: Select all
switch( switchValue ) {
  case Number:
    printf( "switchValue is a Number")
would not print what you wanted it to be, just a literal constant.

That said, in in Python is a standard way of checking for membership of a thing among other things; you might call it an idiom but then you might call the whole Python language a bunch of idioms.

The snippets 2,3 4 from your post are incomparable with that one as the 2nd one is long and cumbersome and ugly and ##3&4 using "switch" are 3 times longer than #1 and more importantly probably don't produce the desired result.

What is your question exactly? is it "are there other Python idioms using operator 'in'"? Or is it "are there other Python idioms at all?" -- in any case, you must be kidding us.
ochichinyezaboombwa
 
Posts: 200
Joined: Tue Jun 04, 2013 7:53 pm

Re: Design Patterns / Idioms

Postby micseydel » Wed Dec 11, 2013 2:05 am

I am not entirely clear on what your question is either. I don't really see much comparability in the two pieces of example code between different languages. The equivalent in Python to a switch is simple if-elif-else branching. You are correct that the two bits of Python you used are more or less equivalent. But I'm not sure what you mean when you say
lseki wrote:I found that these two implementations are similar in reversing the order of the object calling the method, and its argument.

Is it a kind of design pattern or idiom, well known by the language developers?

It is documented (though admittedly not intuitive) that Python has magic methods for which something like using the in keyword corresponds to a specific method, usually (always?) staring and ending with a double underscore. As this relates to "other cool patterns" as you'll see from the link there are tons and many of them are very useful.

As for idioms... I suppose technically speaking this is idiomatic in the sense that other languages do operator overloading differently, and so it varies by language. By if you speak that way I'm not sure people will understand you. Instead, it would be said that it is idiomatic in Python to use a comprehension over a multi-line loop when possible. We use this language because it is notable that although you are allowed to write your Python like you do your Java, creating a container then looping to fill it, Python can and encourages you to do so in a single concise line. Similarly you can do string concatenation in a loop in Python and you can do it in other languages too, and under certain circumstances that will turn out ok however the idiomatic way to do so is to create a list then use str.join().
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1507
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: Design Patterns / Idioms

Postby lseki » Thu Dec 12, 2013 2:09 am

I'm sorry, my post was unnecessarily incomprehensible.

I was studying how to create a python-alike language compiler, just a college mini-project
Although not specified, I found interesting the Python in statement, and I asked myself "How would I program it?".
I thought something ugly like this:

Code: Select all
class MyClass:
  def __init__(self, value=None):
    self.value=value
  def my_in_method(self, aList):
    for n in aList:
      if self.value is n:
        return True
    return False

myObject = MyClass(1)
myObject.my_in_method([1, 2, 3]) # => True
myObject.my_in_methoed([2, 3]) # => False


but I read that Python does it much more generically and concise:
http://effbot.org/pyref/in.htm
It just calls
Code: Select all
 aList.__contains__(myObject)

method, who does all the job

It looked brilliant for me.

***Aother Day, Another Occasion***
I discovered that the Groovy language allows switch-case statement with case of whatever type I want.
So I can call

Code: Select all
switch (switchValue){
  case "stringLiteral":
    foo()
  case 1: // Integer type
    bar()
  case MyClass: // user-defined class
    baz()
  case ~/A Regular Expression/:
    qux()
}


And I asked myself "How would I program it?". No idea. Then I read here how it's done:
http://groovy.codehaus.org/Logical+Branching

It just overloads the isCase() method for each type, like
Code: Select all
  String.isCase(switchValue)
  Integer.isCase(switchValue)
  MyClass.isCase(switchValue)
  Pattern.isCase(switchValue)


I found these two solutions similar, in inverting the caller object and the method parameter.
And I thought "Wow, I wanna see more stuff like this!", "Maybe this kind of approach is very common for the language designers".
lseki
 
Posts: 2
Joined: Tue Dec 10, 2013 12:37 am

Re: Design Patterns / Idioms

Postby snippsat » Thu Dec 12, 2013 6:15 am

There is no build in switch-case statement in Python,and it's not needed.
It's normal to use dictionary,Class or sometime simple like if,elif,else.
The topic with switch-case statement has been up a lot of times,in PEP 3103 it was rejected.
So it`s several ways to this in Python,one way with dictionary or more here
Code: Select all
def switch_case(case):
    return {
    "blue": "The sea is blue",
    "green": "Grass is green",
    "yellow": "Sand is yellow",
    }.get(case, "Wrong value")

print switch_case('blue')
User avatar
snippsat
 
Posts: 296
Joined: Thu Feb 21, 2013 12:04 am


Return to General Discussions

Who is online

Users browsing this forum: No registered users and 2 guests