Today I Learned

A collection of small things I've learned, presented in a collapsible format.

Assertions for quick input validation Aug 20, 2025

In an interview setting, the assert statement provides a quick way to validate input without messing around with throw/raise syntax. I have a tendency of mix up the error handling syntax of different languages.

Instead of this verbose approach:

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

you can do something as simple as

def divide(a, b):
    assert b != 0, "Cannot divide by zero"
    return a / b

It’s a one-liner, the messages are right there, and you’re already dipping your toes into testing rather than punting validation to a later point you might never have time for.

Python binarytree library for tree visualization Aug 18, 2025

Working with binary trees has two major annoyances:

  • building them
  • printing them

I found this library, binarytree that maps pretty close to my definition of a node:

class Node:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

but, it also lets me build trees, or represent existing trees.

Represent existing trees

For a typical sample tree, there’s no more of a need to mess around with tabs and spaces, and labour to make this understandable.

>>> from binarytree import Node
>>>
>>> root = Node(1,
...     Node(2,
...         Node(4,
...             None, Node(7)),
...         Node(5)
...     ),
...     Node(3,
...         Node(6,
...             Node(8), Node(9))
...     )
... )
>>>
>>> print(root)
      __1______
     /         \
  __2         __3
 /   \       /
4     5     6
 \         / \
  7       8   9

Creating a random tree

>>> from binarytree import tree
>>>
>>> my_tree = tree(height=3)
>>> print(my_tree)
    ____14___
   /         \
  9          _3__
 / \        /    \
4   0      11     6
     \           / \
      5         7   8

Counterpoint: You’re probably not going to be able to use it in interviews. Here’s a link to a video with pragmatic suggestions for that scenario.

Python doctests for inline testing Aug 16, 2025

I’ve been going through Composing Programs by John DeNero, and have been picking up little tricks of the trade when it comes to writing code in Python.

The doctest module allows you to write tests directly in docstrings by mimicking what you might see in the REPL.

Simply write >>> followed by Python code and the expected output on the next line.

def add(a, b):
    """
    Add two numbers.
    
    >>> add(2, 3)
    5
    >>> add(-1, 1)
    0
    """
    return a + b

Run with

python -m doctest filename.py

I’ve also noticed that docstrings in FastAPI automatically get converted into descriptions in the OpenAPI documentation. It seems there’s more to docstrings than meets the eye. My initial impression was that this makes code hard to read.