Search code examples
pythonkeyword-argumenttry-except

Python method to try another arbitrary method until it runs without error?


I am trying to create a method to run an arbitrary method passed to it until it runs without errors.

    def multiTry(method, sArg, **kwargs):
        """
        Attempt a specified method until it runs without error.
        Inputs:
          method:  method to be tried until it runs without error
          sArg:  string of all arguments to be passed to method
          kwargs:  all arguments needed for method
        """

        for key, value in kwargs.items():
            eval(key = value)

        bDone = False
        while not bDone:
            try:
                method(eval(sArg))
                bDone = True
            except:
                pass

    multiTry(method=methodToRun, sArg="myString, myNum", myString="hello", myNum=5)

The goal is to repeatedly try:

methodToRun("hello", 5)

...until it runs successfully, where methodToRun is any method and the arguments are any arguments.

I understand both the eval statements are used incorrectly. Probably there is a completely different way to achieve the same goal? I have a number of methods to individually run until successful, and would not like to place every one of them in in-line try-except blocks.


Solution

  • You're pretty close. Something like this should do what you need:

    def multiTry(method, **kwargs):
        while(1):
            try:
                method(**kwargs)
                return
            except:
                pass
    
    multiTry(method=methodToRun, myString="hello", myNum=5)