Claude AI and Python @steamroll_errors

These errors can't stop me because I can't read!

Published: 12/3/2026

D.W. from Arthur stating 'That sign can't stop me because I can't read!' while staring at a sign which clearly states 'No girls allowed.' on a bedroom door.
D.W. from Arthur stating 'That sign can't stop me because I can't read!' while staring at a sign which clearly states 'No girls allowed.' on a bedroom door.

While it is not common, there have been a few instances in the past years where I need my Python function to finish running whether it encounters errors or not. Rather than wrap every single line of code with a try-except-pass block I've decided to create a more programmatic solution to this problem in the form of an easy-to-use decorator!

GitHub Repository

The final code for this project is available on GitHub. I encourage you to download the decorator and try it out for yourself.

AI Use Disclosure

Before I get too far into the details of this project I would like to be upfront about my use of Claude AI to help create this project. This was my first attempt at using Claude Code on a project and I must say I was pleasantly (and somewhat horrifically) surprised at its capabilities!

Admittedly, Claude did most of the heavy lifting for the actual Python code although the idea (and many of the initial debug efforts) had already been implemented by myself in the past.

This article and its contents were written solely by myself. I'm not that lazy. Just regular lazy.

I will also note that Claude made a few interesting mistakes / questionable decisions along the way. I discuss these at the end of this post. 😊

Inspiration

My inspiration for this approach actually comes from National Instrument's TestStand which features a "continue on fail" setting for it's steps such that the broader test suite continues to execute even if a particular test were to fail its test conditions.

I've extended this approach beyond high-level test sequencing to instead encompass any instructions imaginable. In short, if I have a function and I need as much code within that function to execute as possible then this decorator is my best bet.

As a bit of a contrived use-case, imagine a system which initializes a connection to a vast array of dissimilar peripherals. The peripherals each have their own unique set of quirks which may cause them to fail at any time, even during initialization. Our control system (the Python code) should cleanly close any connections to such peripherals if any unhandled error is encountered during operation. Let's suppose that the system will attempt to close its connections to peripherals A thru Z in alphabetical order. However, the most common error I find with this approach is that unrelated errors near the beginning of this "shut down" sequence crash the program entirely and prevent it from safely closing out most of the other connections. Then, rather than dealing with a single stalled peripheral which needs to be restarted / cleaned up manually you instead end up with dozens of stalled peripherals which are still awaiting input from a program which is no longer running.

A poorly drawn doodle of an operator singing 'la la la' while driving a steamroller over a crowd of stick figure people who are labeled 'errors'.
The mental image I had in mind when naming this Python decorator.

Using standard Python, the approach to fix this might be to wrap every single line of code in the shutdown sequence with a try-except-pass (or otherwise handle every error appropriately but that is not always realistic). By doing so, we can effectively "skip" any lines of code which cause an error and still continue to close as many connections as possible before exiting the program. Obviously this still leaves some peripherals in a hanging state, but better a few than the majority.

This solution, however, presents another problem: a massive mess of try-except-finally boilerplate which no one wants to look at.

What if, dear reader, there were instead a programmatic method which could wrap every line of Python source code in a function with a try-except-pass statement at runtime?

Well, look no further than the @steamroll_errors decorator!

Problem Statement

With that idea in mind there were still a few goal posts which the proposed Python decorator needed to fulfill. Most importantly were the following four:

  1. The decorated function must still play nice with a debugger.
  2. The decorator must play nice with other decorators on the same function.
  3. The caller should have the option to specify which Exception types should propagate through the decorated function and into the calling scope.
  4. The caller should be able to optionally log any "steamrolled" errors rather than always handle the event in complete silence.

The first goal point listed above is especially important. My initial attempts at this task successfully wrapped the decorated function's code within try-except-pass blocks however they did not preserve information about which file and line number the original source code occurred at. This cause the Python debugger to step through the decorated function in bizarre ways which were impossible to decipher much less debug.

The Bumps Along the Way

There were a couple of major hurdles to implementing this decorator which I'd like to discuss.

Infinite Recursion

First and foremost, when modifying the source code for the decorated function the @steamroll_errors decorator itself would be passed along for the ride. This would cause the decorator to try and wrap its own statements within try-except-pass blocks which would lead to an infinite recursion which crashes Python. Not ideal.

Finding this error was a bit confusing, I'll admit. However, fixing this issue was fairly straightforward: strip the decorator from the source code which was passed back in to be modified.

Handling Nested Code Blocks

Next up, there was an issue related to nested code blocks such as for, while, if-elif-else, with, etc. statements. Python's abstract syntax tree (AST) considers each of these statements to be a separate node. If we were to simply iterate over the "code" within each function then we would only see the for, etc. statements which live at the top level and not their internal lines of code. This is not aligned with the intended purpose of the decorator. Instead, we want to recurse into each of these blocks and wrap each of their internal lines of code with try-except-pass as well. That also holds true for nested blocks such as for-if-else, etc. The solution here was to create a recursive function for modifying the source code which repeats for such statements. From there we just needed a clearly defined base case for the recursion. In this case we stop recursion when one of the following are encountered: an individual expression such as assignment, a raise statement, OR a call to an external function (or any other change of scope for that matter). This limits the modification of source code to a well-defined scope (just the current function) and prevents the deluge of bugs which would ensue if we were to recursively wrap ALL of Python's standard library in try-except-pass statements.

There are three other special cases to be aware of here:

  1. Nested def, async def, and class statements.
  2. Scope declarations: global and nonlocal.
  3. try blocks which are internal to the decorated function.

Nested def, async def, and class statements are technically handled by the "change of scope" rule from above. Internally, we use the ast library to check the code to be modified against any of these statement types and if it matches we simply skip the modifications for that node.

Scope declarations are not modified because these simply update where the function looks for the particular name when used within its definition. In fact, wrapping these statements risks altering the scope in which they are evaluated and may cause them to lose their desired effect within the original function.

Finally, try blocks which are internal to the decorated function MUST be allowed to raise errors to at least the corresponding except block or else we may interfere with the function author's original control flow. I.e. the original function could have very well handled the raised error appropriately but if the decorator were to steamroll it at the exact moment the raising line of code executes then the original error handling would never be invoked and we would needlessly steamroll a recoverable error. In this case, we want to treat the try-except as a single atomic unit to be wrapped in an outer try-except-pass layer meaning we only steamroll the error if it manages to escape the original function's own error handling. However, there is an exception to this exception! else and finally blocks which follow a try block will still have each line of their code wrapped as usual.

Adding Sensible Error Messages

There were a few errors which I could foresee end-users making when using this decorator which I tried to preempt and provide sensible error messages for. These were:

  1. Attempting to decorate Python code which isn't a def or async def.
  2. Attempting to pass in a Python Exception type rather than an iterable of types (it's easy to forget the brackets when you only have a single element in your errors_to_propagate argument).

Both of these are fairly straightforward. In the first case, we check the type of the source code's AST node against the ast.FunctionDef and ast.AsyncFunctionDef types. If it doesn't match then we simply raise a TypeError explaining that the decorator must be used DIRECTLY before a def or async def statement. Conveniently, this also captures cases where other decorators appear between the @steamroll_errors decorator and the def statement. In this case, the error message clarifies that the order of the decorators should always end with @steamroll_errors. This is confirmed to work with all your usual decorators including @static_method, @property, and both the @_func_name_.setter and @_func_name_.deleter decorators which coincide with the @property decorator.

Finally, if an Exception type is provided directly to the decorator then a TypeError is raised informing the user that the decorator expects an iterable of Exception types and not just a single entry. This one was somewhat tricky to implement because it passes a callable() check I previously had in the code. To fix this I simply re-ordered the checks to start with an isinstance(..., type) and issubclass(..., Exception) check ahead of the callable() check.

Solution

I'm proud to say the final product speaks for itself and passes all test cases that myself and Claude could think of. Moreover, the logger works well with a wide range of options including callback functions, logging.Logger from the Python standard library, and any object supporting the def write(self, s: str, /) -> object: ... function signature. This last option is particularly easy to use since you can just feed in a TextIOWrapper directly from a typical open() call and immediately start logging which errors were steamrolled by the decorator.

Debugger Compatibility
An example of the @steamroll_errors Python decorator working properly within a debugpy session.
An example of the @steamroll_errors Python decorator working properly within a debugpy session.

Furthermore, the decorator plays nicely with debuggers. It does add a bit of a strange effect where the same line of code must be "stepped over" twice in order to progress the debugger. I expect because it's really executing multiple operations for every single "line" of code within the decorated function. However, I consider this to be acceptable and not in urgent need of fixing.

This was achieved using a single line of crucial code which ensures that the line number information from the original function is preserved going forward into the modified code such that the debugger can still point towards the correct code in its tracebacks:

# Keep line numbers pointing at the original file so tracebacks stay meaningful.
ast.increment_lineno(tree, code.co_firstlineno - 1)
Example Usage

Below is example code borrowed from my GitHub repo's README.md of the decorator in action.

Without arguments...

# Use the decorator by itself (without arguments) to achieve default behavior.
# I.e. all unhandled Exception types will be steamrolled without logging.
@steamroll_errors
def bad_function(x: int, y: float) -> complex:
    b = 1 / 0  # raises ZeroDivisionError
    a = int("hello")  # raises ValueError
    d = open("./fake_file.txt", "a")  # raises FileNotFoundError

    o = 3 + 3  # lines which don't produce errors go through the same as usual. :)
    k = float(3.14)

    return x + (y * 1j)

With optional arguments...

# Alternatively, the decorator takes two arguments:
# 1) errors_to_propagate: Iterable[type[Exception]] -> An iterable of
#   Exception types which should *not* be steamrolled and allowed to
#   propagate out of the decorated function.
# 2) logger: logger: Callable[[SteamrolledErrorLog], object]
#    | logging.Logger
#    | logging.LoggerAdapter
#    | SupportsWrite
#    | None = None
#   -> A keyword only argument for either a callback function which takes
#   a SteamrolledErrorLog as its sole argument OR a logging.Logger object
#   from the Python standard library OR an object which supports the `def
#   write(self, s: str, /) -> object: ...` function call such as a
#   TextIOWrapper returned from a typical `open()` call in Python OR None
#   which is the default argument and produces no logs for any errors which
#   are steamrolled.

ERROR_LOGGER = open("./steamrolled_errors.log", "+a", encoding="utf-8")


@steamroll_errors([FileNotFoundError, TypeError], logger=ERROR_LOGGER)
def bad_function(x: int, y: float) -> complex:
    b = 1 / 0  # raises ZeroDivisionError
    a = int("hello")  # raises ValueError
    d = open("./fake_file.txt", "a")  # raises FileNotFoundError

    o = 3 + 3  # lines which don't produce errors go through the same as usual. :)
    k = float(3.14)

    return x + (y * 1j)

if __name__ == "__main__":
    # FileNotFoundError propagates out of this function and crashes the program.
    bad_function(100, 2.77)

With the @steamroll_errors decorator present each of these functions continues chugging along even if it were to hit an errant line of code such as b = 1 / 0. Neat!

Remarks on Claude.ai

I found Claude to be incredibly useful when working on this project and was honestly shocked at how well it handled a somewhat advanced use case of Python. However, there were a few quirks I noticed when working with Claude on this project.

Chief among them were as follows:

  1. Claude consistently tried to reword my decorator and internal code to refer to "steamrolling errors" as "swallowing errors". This makes sense as well, but it was oddly insistent on using its own naming scheme (I liked mine better :P).
  2. Claude initially wrote code to steamroll anything inheriting from BaseException. I definitely did not want this behavior and re-wrote the code to only steamroll types which subclass Exception. Again, Claude was oddly insistent that this be BaseException despite my explicit remarks against it. As you may well know BaseException here would cause KeyboardInterrupt, SystemExit, GeneratorExit and BaseExceptionGroup to all be steamrolled as well. This is HIGHLY undesirable behavior as it breaks many of Python's core functions including explicit operator instructions to halt the program. Perhaps Claude is trying to spare its software brethren...
  3. I had initially instructed Claude to deliberately wrap all lines of code within a try-except-else-finally structure (including the try and except blocks). However, I later realized that this would break the original function's attempts at proper error handling even if they were likely to succeed. This is definitely undesirable behavior in the context of this decorator. Nevertheless, Claude went through with the edit and gave no pushback or recommendations to the contrary. I'm a bit surprised that it can so thoroughly understand what needs to be done to implement what I had requested yet fails to catch, or at least fails to flag, such a major oversight in the design.
Closing Thoughts

I had a lot of fun working on this project. Both during my initial attempt (not documented here) and this latest attempt with Claude assisting. It was very insightful as far as learning just how advanced these AI tools have come since I last checked them out in college (2022-ish).

I hope this Python decorator is as useful to others as it has been to myself. Just be mindful of where you go slapping it!

Until next time! end mark