Build Usable APIs

Clément Thiriet March 24, 2024

You are tasked to build a CLI in Python.

Instead of writing that:

import argparse

if __name__ == "__main__":
	parser = argparse.ArgumentParser()
	parser.add_argument("--dataset")
	parser.add_argument("--epochs")
	parser.add_argument("--lr")
	args = parser.parse_args()
	
	model = Transformer()
	
	for i in range(args.epochs):
		...

Do that:

import argparse

def train(dataset, epochs, lr):
	model = Transformer()
	for i in range(args.epochs):
		...

if __name__ == "__main__":
	parser = argparse.ArgumentParser()
	parser.add_argument("--dataset")
	parser.add_argument("--epochs")
	parser.add_argument("--lr")
	args = parser.parse_args()
	
	train(**args)

Why? Because you can use this program in multiple ways.

As a CLI,

python lm/train.py --dataset=tinystories --epochs=10 --lr=10e-3

And as an API,

from lm import train

# complex logic here...
train(dataset="tinystories", epochs=2, lr=10e-3)

# rest of the function

Your software is more usable.