jml's notebook

Functions without parameters

Functions without parameters

Why do functions have parameter lists?

def add(x, y):
    return x + y

Here, x and y are formal parameters of add. When you want to call the function, you specify arguments (also called “actual arguments”), e.g.

add(x=2, y=3)

Why do we bother to enumerate the parameters, rather than write code like this?

def add:
    return x + y

We could still call it with add(x=2, y=3) and Python would know how to assign which value to which parameter, so it’s not a hard constraint. So why don’t we do it?

Here are three reasons I can think of.

It makes functions harder to use. To call a function, you need to know its parameter list. The only way to determine the parameter list is to read through the entire implementation and take notes.

This is fine for add and mul, but reading through ten, twenty or even fifty lines of code to figure out parameters is going to be tedious and error prone.

You can’t tell mistakes from intent. Without a formal parameter list, any undeclared variable becomes a parameter. If you misspell a name, that becomes a new parameter, and you won’t be able to spot the mistake while you’re writing the function (which is when you want to spot it). You’ll only spot it when you are trying to use the function (which is when you are trying to get something else done).

It makes composition harder to follow. Imagine we had a similar function:

def mul:
    return x * y

How would you use add and mul to say (2 + 3) * (4 + 5)?

mul(x=add(x=2, y=3), y=add(x=4, y=5))

I guess that could work, but it requires getting a lot of things right. Perhaps someone more creative than me could come up with an example that doesn’t work at all.

Maybe you can think of more reasons for why we want to have formal parameter lists for our functions.

Now we’ve got that out of the way, I have another question.

What’s the difference between a function and a template?

<head><title>{{ title }}</title></head>
  <h1>{{ title }}</h1>