What is the point of passing keywords equal to `None` as parameters in a function?

Viewed 2564

I am trying to translate a Python Voronoi Generator to Java but I am not very familiar with keyword arguments and I am confused by the keyword argument that is written as a parameter of a function.

I've read this question, but it only covers calling arguments, not defining them.

It seems like the function is just setting a and b to None. I don't understand why that is necessary. Why not just type None instead of using parameters like that?

What is the point of using keyword parameters equal to None in function definitions?

The function:

class Arc:
    p = None
    pprev = None
    pnext = None
    e = None
    s0 = None
    s1 = None

    def __init__(self, p, a=None, b=None):
        self.p = p
        self.pprev = a
        self.pnext = b
        self.e = None
        self.s0 = None
        self.s1 = None
4 Answers

Keyword arguments can have a default value. In this case, the default value of a and b are None. This means that when these arguments aren't passed into the function, a and b are set to None.

Example:

def func(a=None):
    print(a)
func()
>>>None

But if you do something like this:

def func(a):
    print(a)
func()
>>>TypeError: func() missing 1 required positional argument: 'a'
def __init__(self, p, a=None, b=None):

That line is defining the __init__ method, which you can think of as a constructor for the class. It's not calling the method.

Setting a and b equal to None in the method definition makes None their default value. This makes them optional when you call the method. (So you can call the method with 1, 2, or 3 parameters.) If you don't pass in values for a and b, None will be used. It's common in Python to use optional parameters in place of overloading methods.

This is a concept called default value.

Using this syntax, the caller can choose whether to specify a value for every such argument or use the default one.

Suppose you have a method that has a default behavior, but you want to reserve the possibility to change it willingly. This give you this power.

Consider the following example:

def custom_method(msg, prefix=None):
  tag = prefix if prefix else ''
  print(tag + msg)

Now, as a user of this API, you can choose to use a prefix, or avoid it:

custom_method('Dude', 'Hi')
# Prints 'Hi Dude'

Or:

custom_method('Dude')
# Prints 'Dude'

This is the Python syntax for default arguments, or optional argument.

Arguments which are declared with a default value, will receive that default value if they are not passed in the function call, and will receive what is passed in the other case.

Here Arc(p) is the same as Arc(p, None, None), but you could use:

a1 = Arc(p)
a2 = Arc(p, a1)

and then a2.pprev will be a1.

But there are some caveats with mutable default arguments... be careful with them or better avoid them until you are more proficient at Python.

Related