
Member-only story
Extending the Python Syntax
How to add sugar to the Python syntax with main wrappers
I love Python. It’s an extremely powerful language that’s very simple to write and understand. It also has an extensive ecosystem of libraries that allow you to do pretty much anything you can think of (even fly). Recently, it has become the lingua franca of Data Science and Machine Learning. I use it constantly in my day job, so I’d say I’m fairly proficient at it (I do have Python readability at Google after all 😏¹).
However, Python is not perfect. I’ve recently started learning Lisp in my free time.² While learning, I stumbled across what I think is a very cool (but minor) feature of Lisp. When defining functions, Lisp allows you to use previous arguments as default values.
For example, suppose you’re writing a make_rectangle
function which takes as input the x, y
coordinates of the top-left corner, width
, and height
and returns the x, y
coordinates of the 4 corners of the rectangle. We can do this pretty easily in Python:
Now suppose that we want the function to return squares if it’s only passed the width
argument. If you never programmed before, you might expect that a reasonable thing to is to set height=width
, like so:
Unfortunately, it’s not valid Python. If you try to run it, you’ll get an error:
NameError: name 'width' is not defined.
Personally, I feel that this is a failing of the language. Sure, it’s pretty easy to work around the syntax and get a similar behavior: