|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Stop making mediocre tutorials.The best tutorials are video! Camtasia Studio makes it easy to create engaging, buzz-building screen videos at any size, in any popular format. Download the free trial!
|
|
#1
|
|||
|
|||
|
Lazy list of functions
Hi folks,
I'm trying to write a test script without dozens of ifs. I was hoping to put all my tests into a list of functions and then do something like a left fold over it and add embelishments for printing the name of the test and its result. Trouble is, I can't seem to create that list of functions because python just evaluates them straight away and puts the results in the list instead. This seems to belie the statement that functions are first class objects. Is there something like lisp's tick to solve this, or should I resort to comefrom? Ad. |
|
#2
|
|||
|
|||
|
The following has probably serious consequences or side effects, but I leave that to more knowledgeable persons.
How about having a list of strings where each string is the name of a function, and then eval()ling each name? |
|
#3
|
||||||||
|
||||||||
|
The following utilizes a tuple of functions. Functions are first-class objects in Python.
Python Code:
Python Code:
|
|
#4
|
|||
|
|||
|
Thanks folks,
I think it's even easier than that, but your examples showed me where I was going wrong. I was writing my list as [test1(), test2(),test3()] so I guess it'll all work tomorrow if I just remove the ()s. Thanks again, Ad. |
|
#5
|
|||||
|
|||||
|
yes because the () indicate to the compiler that you wish to call the function rather than pass a pointer to it
found this function test code in a book, dont know if its quite what you're looking for but might give you some help: Python Code:
|
|
#6
|
|||
|
|||
|
I was actually thinking of something like this:
def a(): print "A" return "OK_" def b(): print "B" return "ERROR" def c(): print "C" return "OK" def passall(fl): if (len(fl)): d,f,e = fl[0] res = f() print d, res if res[:len(e)]==e: passall(fl[1:]) passall([("TryA",a,"OK"), ("TryB",b,"ERROR"), ("TryC",c,"OK")]) So that the script will give up at the first mismatch. Is there a more elegant way of getting the head and tail of the list, ideally something like declaring the parameter as f:fl like you can in haskell? My only real problem now, is that I no longer have an excuse to use the sublime 'comefrom'. Ad. |
|
#7
|
|||
|
|||
|
Please use code tags. Your program structure is lost without them. Following is some suggested code:Test:
|
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > Lazy list of functions |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|