views:

237

answers:

5

Hi,

I wonder if we can do that in python, let's suppose we have 3 differents functions to processing datas like this:

def main():
  def process(data):
     .....
  def process1(data):
     .....
  def process2(data):
     .....
  def run():
     test = choice([process,process1,process2])
     test(data)
  run()

main()

Can we choice one random function to process the data ? If yes, is this a good way to do so ?

Thanks !

A: 

Yes. I don't see why not.

codeape
+3  A: 

Sure is!

That the nice thing in Python, functions are first class objects and can be referenced in such an easy fashion.

The implication is that all three methods have the same expectation with regards to arguments passed to them. (This probably goes without saying).

mjv
You mean `function`, right? A method is a kind of function. In the OP's code process1, process2, and process3 are functions.
lost-theory
unfortunatly it doesn't work with my example, can you provide one please ? thanks !
n00bie
@lost-theory, right! I edited accordingly. `function` is the more generic and and appropriate term here (although this technique does work as well for bound `methods`, which as you said are a special kind of function)
mjv
+1  A: 

Just use the random number module in python.

random.choice(seq)

This will give you a random item from the sequence.

http://docs.python.org/library/random.html

Tim Snyder
A: 

Your code will work just like you wrote it, if you add this to the top:

from random import choice

Or, I think it would be slightly better to rewrite your code like so:

import random

def main():
  def process(data):
     .....
  def process1(data):
     .....
  def process2(data):
     .....
  def run():
     test = random.choice([process,process1,process2])
     test(data)
  run()

main()

Seeing random.choice() in your code makes it quite clear what is going on!

steveha
+3  A: 

Excellent approach (net of some oversimplification in your skeleton code). Since you ask for an example:

import random

def main():
  def process(data):
     return data + [0]
  def process1(data):
     return data + [9]
  def process2(data):
     return data + [7]
  def run(data):
     test = random.choice([process,process1,process2])
     print test(data)
  for i in range(7):
    run([1, 2, 3])

main()

I've made it loop 7 times just to show that each choice is indeed random, i.e., a typical output might be something like:

[1, 2, 3, 7]
[1, 2, 3, 0]
[1, 2, 3, 0]
[1, 2, 3, 7]
[1, 2, 3, 0]
[1, 2, 3, 9]
[1, 2, 3, 9]

(changing randomly each and every time, of course;-).

Alex Martelli
Great !My problem now is i would like to print which one is used : .... test = random.choice([process,process1,process2]) print "using %s"% (test) ....using <function process1 at 0x1775410> , how can i remove the "... at 0x1775410>"Thanks !
n00bie
Just `print "using", test.__name__`.
Alex Martelli