2

Example: https://docs.python.org/3/library/functions.html#func-bytearray

class bytearray([source[, encoding[, errors]]])

Normally I just figure this out through examples, but I want to learn why the format of optional parameters are written in this way. Specifically:

  1. What should I interpret when an optional parameter is within a [] of another parameter? If [a[, b]], then what does that mean for b in relation to a? If both are independent of each other, except by order, then why is b enclosed in the bracket for a?

  2. For second and other parameters, why is there a comma preceding it within the brackets? What makes it different between [a[, b]] and [a[b]] given whatever the relation between the two from the first question above?

  3. How is this format advantageous or suitable in situations than the one below besides us not having to specify/write the parameter names?

class bytearray(source = default_value1, encoding = default_value2, errors = default_value3)

2

1 Answer 1

4

These are optional parameters, and there is a dependency to their 'optionality'.

Given class bytearray([source[, encoding[, errors]]]), the valid uses will be

class bytearray()
class bytearray(source)
class bytearray(source, encoding)
class bytearray(source, encoding, errors)

The nested brackets indicate that, for example, you may only specify encoding parameter when you have already specified the source parameter.

Why is there a comma inside the bracket? Because the comma is part of the optional parameter; if you don't choose to specify the parameter then you shouldn't provide the comma.

How is this advantageous over three optional parameters? As above - sometimes a parameter only makes sense when another parameter is provided. In this case the library author has decided they don't want to allow you to provide the encoding parameter unless you have provided the source parameter.

Sign up to request clarification or add additional context in comments.

Comments