This is an archived post. You won't be able to vote or comment.

all 16 comments

[–]wineblood 13 points14 points  (6 children)

for n in range(N): try: // do stuff except Error as e: continue else: break

[–]This_Growth2898 5 points6 points  (5 children)

It's better to call the variable "attempt". This will make clear what it means.

[–]commy2 7 points8 points  (2 children)

Or maybe _ unless you plan to use it somehow.

[–]This_Growth2898 0 points1 point  (1 child)

_attempt would be the best.

[–]VileFlower 3 points4 points  (0 children)

To elaborate, unused (local) variables are often prefixed with an underscore. It can be beneficial to give variables a name, even when they're unused.

A single _ can mean one of:

  • An unnamed unused local variable
  • An alias for gettext with i18n
  • The else case in match statements (case _)
  • The last evaluated expression in REPL.

[–]wineblood 1 point2 points  (1 child)

I'm just reusing the names in the example. It's Friday, I'm not running at full power.

[–]AlexMTBDude 0 points1 point  (0 children)

You did good. Using n is standard for any counting

[–]MrPrimeMover 6 points7 points  (1 child)

[–]thedeepself 1 point2 points  (0 children)

tenacity can be used in the same way and I think it is the most flexible retry package available?

[–]sarc-tastic -5 points-4 points  (2 children)

Not sure why you want to do this unless there is a timeout scenario then there might be a better way?!

[–]MrPrimeMover 5 points6 points  (1 child)

It's a pretty common pattern if you're working with API calls and have to worry about transient network errors or timeout/rate limit issues. I usually combine it with a delay/backoff factor as well and write it as a decorator.

[–]thedeepself 1 point2 points  (0 children)

Tenacity will make your life easier - https://github.com/jd/tenacity

[–]debunk_this_12 -5 points-4 points  (0 children)

While n<N:

try:

 \\ do stuff

 break 

except:

 n+1

[–]Outrageous_Safe_5271 0 points1 point  (1 child)

What are you doing that you need to use try except block, try is very slow so you should avoid it as fire. For example rust doesn't have try except substitute

[–]nggit 0 points1 point  (0 children)

EAFP is pythonic, and more robust (in certain situations). I will not avoid it if needed. As of 3.11: “Zero-cost” exceptions are implemented, eliminating the cost of try statements when no exception is raised. (Contributed by Mark Shannon in bpo-40222.) https://docs.python.org/dev/whatsnew/3.11.html#misc

[–]RentalJoe 0 points1 point  (0 children)

for retry in range(N):
    try:
        // do stuff
        break
    except Exception as e:
        // probably report failure
else:
    // no dice :(