473,804 Members | 3,433 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

More elegant way to try running a function X times?

Hello

As a newbie, it's pretty likely that there's a smarter way to do this,
so I'd like to check with the experts:

I need to try calling a function 5 times. If successful, move on; If
not, print an error message, and exit the program:

=====
success = None

for i in range(5):
#Try to fetch public IP
success = CheckIP()
if success:
break

if not success:
print "Exiting."
sys.exit()
=====

Thank you.
Nov 19 '08 #1
9 1597
I need to try calling a function 5 times. If successful, move on; If
not, print an error message, and exit the program:

success = None
for i in range(5):
#Try to fetch public IP
success = CheckIP()
if success:
break
if not success:
print "Exiting."
sys.exit()
Though a bit of an abuse, you can use

if not any(CheckIP() for _ in range(5)):
print "Exiting"
sys.exit()

(this assumes Python2.5, but the any() function is easily
recreated per the docs at [1]; and also assumes the generator
creation of 2.4, so this isn't as useful in 2.3 and below)

Alternatively, you can use the for/else structure:

for i in range(5):
if CheckIP():
break
else:
print "Exiting"
sys.exit()

-tkc

[1]
http://www.python.org/doc/2.5.2/lib/...cs.html#l2h-10

..
Nov 19 '08 #2
Gilles Ganault <no****@nospam. comwrote:
>As a newbie, it's pretty likely that there's a smarter way to do this,
so I'd like to check with the experts:

I need to try calling a function 5 times. If successful, move on; If
not, print an error message, and exit the program:

=====
success = None

for i in range(5):
#Try to fetch public IP
success = CheckIP()
if success:
break

if not success:
print "Exiting."
sys.exit()
=====
for i in range(5):
if CheckIP():
break
else:
print "Exiting."
sys.exit()

Note very carefully that the "else" goes with the "for" and not the "if".

--
\S -- si***@chiark.gr eenend.org.uk -- http://www.chaos.org.uk/~sion/
"Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
Nov 19 '08 #3

On Nov 19, 2008, at 09:09, Gilles Ganault wrote:
Hello

As a newbie, it's pretty likely that there's a smarter way to do this,
so I'd like to check with the experts:

I need to try calling a function 5 times. If successful, move on; If
not, print an error message, and exit the program:

=====
success = None

for i in range(5):
#Try to fetch public IP
success = CheckIP()
if success:
break

if not success:
print "Exiting."
sys.exit()
=====
A little simpler:

for i in range(5):
if CheckIP():
break
else:
print "Exiting."
sys.exit()

The else part will only fire if the for finishes without breaking.
Hope this helps a bit...
Nick Fabry



Thank you.
--
http://mail.python.org/mailman/listinfo/python-list
Nov 19 '08 #4
On 19 Nov 2008 14:37:06 +0000 (GMT), Sion Arrowsmith
<si***@chiark.g reenend.org.ukw rote:
>Note very carefully that the "else" goes with the "for" and not the "if".
Thanks guys.
Nov 19 '08 #5
On Nov 19, 10:21*am, Gilles Ganault <nos...@nospam. comwrote:
On 19 Nov 2008 14:37:06 +0000 (GMT), Sion Arrowsmith

<si...@chiark.g reenend.org.ukw rote:
Note very carefully that the "else" goes with the "for" and not the "if"..

Thanks guys.
And if you end up doing this for several different functions, you can
factor it out with the following decorator:

class MaxRetriesExcee dedError(Except ion):
pass

def retry(n):
def decorator(f):
def wrapper(*args, **kwds):
for i in xrange(n):
r = f(*args, **kwds)
if r: return r
raise MaxRetriesExcee dedError
return wrapper
return decorator

If the number of retries is fixed and known at "compile" time, you can
use the standard decorator syntax:

@retry(5)
def CheckIP():
...

If not, just decorate it explicitly at runtime:

def CheckIP():
...

n = int(raw_input(' Give number of retries:'))
CheckIP = retry(n)(CheckI P)
HTH,
George
Nov 19 '08 #6
Tim Chase wrote:
>success = None
for i in range(5):
#Try to fetch public IP
success = CheckIP()
if success:
break
if not success:
print "Exiting."
sys.exit()

Though a bit of an abuse, you can use

if not any(CheckIP() for _ in range(5)):
print "Exiting"
sys.exit()
I don't see why you speak of abuse, bit of abuse would be, say if you replaced
range(5) by '12345' to win a char; but otoh I think you misspelled any() for all().

Cheers BB

Nov 20 '08 #7
>>success = None
>>for i in range(5):
#Try to fetch public IP
success = CheckIP()
if success:
break
if not success:
print "Exiting."
sys.exit()
Though a bit of an abuse, you can use

if not any(CheckIP() for _ in range(5)):
print "Exiting"
sys.exit()

I don't see why you speak of abuse, bit of abuse would be, say if you replaced
range(5) by '12345' to win a char; but otoh I think you misspelled any() for all().
The OP's code break'ed (broke?) upon the first success, rather
than checking all of them. Thus, it would be any() rather than
all(). Using all() would require 5 successful calls to
CheckIP(), rather than one-out-of-five successful calls.

As for abuse, the "for _ in iterable" always feels a little hokey
to me. It works, but feels warty.

-tkc

Nov 20 '08 #8
Gilles Ganault wrote:
Hello

As a newbie, it's pretty likely that there's a smarter way to do this,
so I'd like to check with the experts:

I need to try calling a function 5 times. If successful, move on; If
not, print an error message, and exit the program:

=====
success = None

for i in range(5):
#Try to fetch public IP
success = CheckIP()
if success:
break

if not success:
print "Exiting."
sys.exit()
Use the for statement's "else" clause: it's there to allow you to
specify code to be executed only when the loop terminates normally.

for i in range(5):
if CheckIP():
break
else:
sys.exit("Could not verify IP address")
.... remainder of program ...

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Nov 20 '08 #9
Tim Chase wrote:
>>>success = None
for i in range(5):
#Try to fetch public IP
success = CheckIP()
if success:
break
if not success:
print "Exiting."
sys.exit()
Though a bit of an abuse, you can use

if not any(CheckIP() for _ in range(5)):
print "Exiting"
sys.exit()

I don't see why you speak of abuse, bit of abuse would be, say if you
replaced range(5) by '12345' to win a char; but otoh I think you
misspelled any() for all().

The OP's code break'ed (broke?) upon the first success, rather than
checking all of them. Thus, it would be any() rather than all(). Using
all() would require 5 successful calls to CheckIP(), rather than
one-out-of-five successful calls.
Right. So it could also be written " if all(not CheckIP()... ". Perhaps more
closely re-telling the OP's ?
>
As for abuse, the "for _ in iterable" always feels a little hokey to
me. It works, but feels warty.
I guess this means you did not learn Prolog before Python ?

Cheers, BB

Nov 20 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
5025
by: Kamilche | last post by:
Is there a more elegant way to change the working directory of Python to the directory of the currently executing script, and add a folder called 'Shared' to the Python search path? This is what I have. It seems like it could be shorter, somehow. # Switch Python to the current directory import os, sys pathname, scriptname = os.path.split(sys.argv) pathname = os.path.abspath(pathname)
2
4266
by: Gary Harvey | last post by:
I have a data intensive program that requires all data to be present in memory. I keep running out of memory at about 2G whenever I run my program. I tried using a 64 bit version of Perl and hit the same limit even though the memory on the machine was 8G. Even with 32 bit addresses, I should be able to use 4G if it is available on the machine. How can I get my perl programs to access more than 2G of memory? Thanks.
17
7390
by: Fresh Air Rider | last post by:
Hello Could anyone please explain how I can pass more than one arguement/parameter value to a function using <asp:linkbutton> or is this a major shortfall of the language ? Consider the following code fragments in which I want to list through all files on a directory with a link to download each file by passing a filename and whether or not to force the download dialog box to appear.
4
10361
by: Bill Dika | last post by:
Hi I am trying to calculate a running total of a calculated textbox (tbAtStandard) in GroupFooter1 for placement in a textbox (tbTotalAtStandard) on my report in Groupfooter0. The problem that I am having is that sometimes the correct total shows up in print preview and sometimes it doesn't. Sometimes it is higher and sometimes it is lower (than the correct amount) and I cannot make any sense of the difference. The difference...
13
1214
by: Edward W. | last post by:
hello, I have this function below which is simple and easy to understand private function ListHeight (byval UserScreenHeight as int) as int if UserScreenHeight < 1024 return 30 else return 50 end if end function
4
1489
by: Iain King | last post by:
When I loop over one list I use: for item in items: print item but often I want to loop through two lists at once, and I've been doing this like I would in any other language - creating an index counter and incrementing it. For example, (completely arbitrary), I have two strings of the same length, and I want to return a string which, at each character
9
1795
by: mathon | last post by:
hi, i already posted an entry because of this problem, unfortunately i havent solved it so far..:( I have created a recursion for the calculation of the power like this: double power(double x, int n) {
10
32845
by: sherifffruitfly | last post by:
Hi all, This is how I'm currently getting Friday of last week. It strikes me as cumbersome. Is there a slicker/more elegant way? Thanks for any ideas, cdj
12
1329
by: Helmut Jarausch | last post by:
Hi, I'm looking for an elegant solution of the following tiny but common problem. I have a list of tuples (Unique_ID,Date) both of which are strings. I want to delete the tuple (element) with a given Unique_ID, but I don't known the corresponding Date. My straight forward solution is a bit lengthy, e.g.
0
10575
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10330
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10076
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9144
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7616
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6851
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5520
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3816
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2990
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.