DEV Community

loading...
Cover image for DTTAW: Exception Driven Fizz Buzz V2

DTTAW: Exception Driven Fizz Buzz V2

fronkan profile image Fredrik Bengtsson ・2 min read

So I have decided I will embrace some of my, sometimes, let's call them "less practical ideas". Therefore, I will do this as a series, Don't try this at work or DATTAW for short. My previous and first post of the series was:

However, I figured I would take on the challenge of removing all if-statements from the code. This was surprisingly easy. The solution:

import sys
import inspect
import traceback

def fizzbuzz(val):
    assert val % 15 != 0
    fizz(val)

def fizz(val):
    assert val % 3 != 0
    buzz(val)

def buzz(val):
    assert val % 5 != 0

def exception_driven_fizzbuzz(val):
    try:
        fizzbuzz(val)
        print(val)
    except AssertionError as e:
        tb = e.__traceback__
        while tb.tb_next:
            tb = tb.tb_next
        print(tb.tb_frame.f_code.co_name)


for val in range(1, 16):
    exception_driven_fizzbuzz(val)
Enter fullscreen mode Exit fullscreen mode

The only difference from last time is that we have swapped the if-statements for assert-statements. In doing so we had to flip the logic checks. Instead of detecting that value is divisible by 3 for the fizz function we assert that it is not divisible by 3. Then if it is divisible by 3 an AssertionError is raised. As we are using AssertionError instead of ValueErrors we also had to modify the error type in the except-statement, but that is it!

Small caveat here, the change from if-statement to asserts actually introduces a bug. This bug is triggered only if you run the script using the -O flag: python -O fizzbuzz_v2.py. If you do, it will just print the numbers instead. The reason is that the -O flag runs the script with optimizations, which includes removing all assert-statements. No assert-statements gives no errors and results in no fizzbuzzing.

I hope this post was entertaining and can inspire you to try some unorthodox coding practices (at home of course). It is a fun way to explore the language where you might find some interesting and actually useful insights.

Discussion (0)

pic
Editor guide