Ghost
Ghost

Reputation: 1523

Try for multiple statements in Python

I need some help/advice on the best approach to do this. I have a block of code in Python, which is basically more or less the same line (a function/method applied to different variables). Now, sometimes, depending on other things, some of those variables may not exist, causing the lines that have any of them to throw an exception.

My goal is to run the block of code allowing the lines with the existing variables to run and the others to be skipped. I have a million workarounds for this, but i wanna see if there is a "clean" way, like, using a try/exception for the "entire" block.

My idea is to do something like this, where a1, a2, a3, etc., are the variables that could or could not exist:

try:
    functionx(a1)
    functionx(a2)
    functionx(a3)
    ...
except:

And somehow, to get that try/except wrap to skip the ones that don't exist, but execute the ones that exist.

Any idea?

Edit: The point is to see if, somehow, i can make the try to "continue" after it gets an exception inside its code block instead of breaking and going to the except.

Upvotes: 1

Views: 105

Answers (3)

voidpointercast
voidpointercast

Reputation: 185

Maybe something like *args or **kwargs will do the trick.

def apply_on(*args):
    for arg in args:
    try:
        functionx(arg)
    except:
        pass

You could then call like:

apply_on(1, 2, 3, 4)

Using kwargs if the name of the "variable" is somehow important:

def apply_on(**kargs):
    for name, arg in args.items():
        try:
            functionx(arg)
        except:
            pass

Usually it is not clean to assume that variables exist or not. Pick some other data structure in this case, like list or dictionary, depending on your use case.

Upvotes: 0

Danielle M.
Danielle M.

Reputation: 3662

Assuming you meant some vars might be None: only run your function on vars that aren't None:

for non_null_var in [v for v in [a1, a2, a3, ...] if v is not None]:
  functionx(non_null_var)

map & filter version:

map(functionx, filter(lambda x: x is not None, [a1, a2, a3, ...]))

If you really mean they aren't defined at all, then, modifying Martin's answer:

for non_null_var in [v for v in ['a1', 'a2', 'a3', '...'] if v is in locals() and locals()[v] is not None]:
      functionx(locals()[v])

Upvotes: 2

Martin Tovmassian
Martin Tovmassian

Reputation: 1438

Based on this answer, you can call your function only after checking the variable exists like so:

functionx(a1) if 'a1' in locals() else None
functionx(a2) if 'a2' in locals() else None
functionx(a3) if 'a3' in locals() else None

Upvotes: 3

Related Questions