DEV Community

Cover image for Don't Try This at Work: Exception Driven Fizz Buzz V2
Fredrik Sjöstrand
Fredrik Sjöstrand

Posted on • Edited on • Originally published at fronkan.hashnode.dev

1

Don't Try This at Work: Exception Driven Fizz Buzz V2

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 DTTAW 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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay