Skip to content

Call another function before retry #361

Closed as not planned
Closed as not planned

Description

@ArcangeloGarbellini

Hello, is it possible to call another function before retrying?
I have a try and except block, and I know that if it fails it is because of a connection issue, so before the next attempt I would like to run another function that reinitialise the connection. Is that possible with the tenacity package?
Thank you

Activity

  1. asqui commented on Sep 1, 2022

    @asqui
    Contributor

    Looking at Before and After Retry, and Logging it is possible to execute an action:

    1. Before any attempt of calling the function (before action)
    2. After a call that failed (including after the last attempt) (after action)
    3. After a failure that is going to be retried (but before the sleep) (before_sleep action)

    None of these matches your use case exactly, but 1 (the before action) sounds like it might be the closest.

    I guess you can either restructure your code to have the connection for the first attempt also established in this action, or to no-op the action on the first attempt.

    Sounds like the enhancement that would meet your needs of executing an action before any retry would be:

    1. Ability to specify an after_sleep action

    Unfortunately this is not currently supported, but I'm sure a PR to add this would be considered.

  2. ArcangeloGarbellini commented on Sep 5, 2022

    @ArcangeloGarbellini
    Author

    Ok, I'll add a PR request. Thanks

  3. vinjana commented on Jun 26, 2023

    @vinjana

    Seems like a duplicate of #298.

    I don't find a corresponding PR.

  4. jd commented on Feb 23, 2026

    @jd
    Owner

    Use the before_sleep callback to run a function between retries:

    def reconnect(retry_state):
        reinitialise_connection()
    
    @retry(before_sleep=reconnect)
    def do_work():
        ...

    Closing as a usage question (duplicate of #298).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions