Python Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me
Go Back   Dev Shed ForumsProgramming LanguagesPython Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
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  
Old April 15th, 2008, 03:48 AM
aamay aamay is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Apr 2008
Posts: 3 aamay User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 11 m 51 sec
Reputation Power: 0
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.

Reply With Quote
  #2  
Old April 15th, 2008, 07:09 AM
SuperOscar SuperOscar is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Jul 2007
Location: Tampere, Finland
Posts: 78 SuperOscar User rank is Sergeant (500 - 2000 Reputation Level)SuperOscar User rank is Sergeant (500 - 2000 Reputation Level)SuperOscar User rank is Sergeant (500 - 2000 Reputation Level)SuperOscar User rank is Sergeant (500 - 2000 Reputation Level)SuperOscar User rank is Sergeant (500 - 2000 Reputation Level) 
Time spent in forums: 16 h 50 m 52 sec
Reputation Power: 12
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?

Python Code:
Original - Python Code
  1. def test1:
  2.     print 'Running test 1...'
  3. # ...and so on
  4. funcs = ['test1', 'test2', 'test3']
  5. for func in funcs:
  6.     eval('%s()' % func)

Reply With Quote
  #3  
Old April 15th, 2008, 08:34 AM
bvdet bvdet is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Mar 2008
Posts: 20 bvdet User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 7 h 39 m 4 sec
Reputation Power: 0
The following utilizes a tuple of functions. Functions are first-class objects in Python.
Python Code:
Original - Python Code
  1. def fdim(s):
  2.     ss = s.split('/')
  3.     return float(ss[0])/float(ss[1])
  4.  
  5. def convertType(s):
  6.     if s != 'None':
  7.         for func in (int, float, fdim, eval):
  8.             try:
  9.                 n = func(s)
  10.                 return n
  11.             except:
  12.                 pass
  13.     return s
Examples:
Python Code:
Original - Python Code
  1. >>> convertType('31/32')
  2. 0.96875
  3. >>> convertType('1,2,3')
  4. (1, 2, 3)
  5. >>> convertType('2.345')
  6. 2.3450000000000002
  7. >>> convertType('2')
  8. 2
  9. >>> convertType('[1,2,3]')
  10. [1, 2, 3]
  11. >>> convertType('[int,float,eval]')
  12. [<type 'int'>, <type 'float'>, <built-in function eval>]
  13. >>> convertType('a string')
  14. 'a string'
  15. >>> 

Reply With Quote
  #4  
Old April 15th, 2008, 11:18 AM
aamay aamay is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Apr 2008
Posts: 3 aamay User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 11 m 51 sec
Reputation Power: 0
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.

Reply With Quote
  #5  
Old April 15th, 2008, 12:52 PM
c-2501 c-2501 is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2005
Location: Scotland
Posts: 28 c-2501 User rank is Corporal (100 - 500 Reputation Level)c-2501 User rank is Corporal (100 - 500 Reputation Level)c-2501 User rank is Corporal (100 - 500 Reputation Level)c-2501 User rank is Corporal (100 - 500 Reputation Level) 
Time spent in forums: 10 h 22 m 21 sec
Reputation Power: 0
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:
Original - Python Code
  1. def testit(func, *nkwargs, **kwargs):
  2.     try:
  3.         retval = func(*nkwargs, **kwargs)
  4.         result = (True, retval)
  5.     except Exception, e:
  6.         result = (False, str(e))
  7.     return result
  8.  
  9. def test():
  10.     funcs = (int, long, float)
  11.     vals = (1234, 12.34, '1234', '12.34')
  12.  
  13.     for eachFunc in funcs:
  14.         print '-' * 20
  15.         for eachVal in vals:
  16.             retval = testit(eachFunc, eachVal)
  17.             if retval[0]:
  18.                 print '%s(%s) = ' % (eachFunc.__name__, eachVal), retval[1]
  19.             else:
  20.                 print '%s(%s) = FAILED: ' % (eachFunc.__name__, eachVal), retval[1]
  21.  
  22. if __name__ == '__main__':
  23.     test()

Reply With Quote
  #6  
Old April 15th, 2008, 09:39 PM
aamay aamay is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Apr 2008
Posts: 3 aamay User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 11 m 51 sec
Reputation Power: 0
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.

Reply With Quote
  #7  
Old April 15th, 2008, 11:03 PM
bvdet bvdet is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Mar 2008
Posts: 20 bvdet User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 7 h 39 m 4 sec
Reputation Power: 0
Please use code tags. Your program structure is lost without them. Following is some suggested code:
Python Code:
Original - Python Code
  1. def a():
  2.     print "A"
  3.     return "OK_"
  4.  
  5. def b():
  6.     print "B"
  7.     return "ERROR"
  8.  
  9. def c():
  10.     print "C"
  11.     return "OK"
  12.  
  13. def passall(*args):
  14.     for t in args:
  15.         res = t[1]()
  16.         print t[0], res
  17.         if t[2] != res:
  18.             print 'Mismatch found'
  19.             return False
  20.     return True
Test:
Python Code:
Original - Python Code
  1. >>> passall(("TryA",a,"OK"), ("TryB",b,"ERROR"), ("TryC",c,"OK"))
  2. A
  3. TryA OK_
  4. Mismatch found
  5. False
  6. >>> passall(("TryA",a,"OK_"), ("TryB",b,"ERROR"), ("TryC",c,"OK"))
  7. A
  8. TryA OK_
  9. B
  10. TryB ERROR
  11. C
  12. TryC OK
  13. True
  14. >>> 

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesPython Programming > Lazy list of functions


Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

 Free IT White Papers!
 
Accelerating Trading Partner Performance
One in five. That's how many partner transactions have at least one error. That is an amazing statistic, particularly given the extraordinary leaps in innovation across the global supply chain during the past two decades. Download this white paper to learn more.

 
Competing on Analytics
This Tech Analysis is designed to help identify characteristics shared by analytics competitors, and includes information about 32 organizations that have made a commitment to quantitative, fact-based analysis.

 
Cost Effective Scaling with Virtualization and Coyote Point Systems
An overview of the industry trend toward virtualization, how server consolidation has increased the importance of application uptime and the steps being taken to integrate load balancing technology with virtualized servers.

 
Five Checkpoints to Implementing IP Telephony
Implementation planning for IP PBX software and IP telephony has become vital as businesses replace discontinued legacy PBX phone systems. This informative whitepaper outlines five "checkpoints" for any implementation plan that will help make IP communications a successful proposition.

 
Hosted Email Security: Staying Ahead of New Threats
In the last two years, email has become a fierce battleground between the nefarious forces of spam and malware, and the heroes of messaging protection. The spam volumes increased alarmingly every month, bringing clever new forms of phishing and virus propagation attacks.