0

I have a for loop that is iteration through a column and doing some xml processing. There are some errors that I am encountering, but rather than just pass them, I would like to save them into a seperate list as part of the output. This is what I have so far:

def outputfunc(column_name):
    output = []
    errors = []
    for i in column_name:
        try:
            tree = etree.fromstring(i)
        except:
            errors.append(i) #basic logic here is that i append errors with i that raise error and then pass
            pass
0

1 Answer 1

1

Elaborating on Carcigenicates comment, if you want to find all errors using the Exception base class, you can change your code to:

def outputfunc(column_name):
    output = []
    errors = []
    for i in column_name:
        try:
            tree = etree.fromstring(i)
        except Exception as e:
            errors.append(e) #basic logic here is that i append errors with i that raise error and then pass

This sets e to the text of the error message. e is then appended to errors. Furthermore, I've removed a nonfunctional pass statement. However, you currently have no way to output errors, so I suggest using

print('\n'.join(map(str,errors)))

Within the scope of outputfunc. Furthermore, as Paul Cornelius suggests, returning your output and errors in tuple format would be useful. This would make your code

def outputfunc(column_name):
    output = []
    errors = []
    for i in column_name:
        try:
            tree = etree.fromstring(i)
        except Exception as e:
            errors.append(e) #basic logic here is that i append errors with i that raise error and then pass
    print('\n'.join(map(str,errors)))
    return output, errors

References

2. Lexical analysis — Python 3.9.6 documentation

Built-in Exceptions — Python 3.9.6 documentation

Sign up to request clarification or add additional context in comments.

1 Comment

An improvement for sure. But I think you should add return output, errors as the last line of the function. As it stands it doesn't do anything useful since output is local and just gets thrown away. I also think it would be better to let the calling code do the printing, in case it wants to do something else with the errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.