python how to define function with optional parameters by square brackets?


I often find some functions defined like open(name[, mode[, buffering]]) and I know it means optional parameters.
Python document says it’s module-level function. When I try to define a function with this style, it always failed.
For example
def f([a[,b]]): print('123')
does not work.
Can someone tell me what the module-level means and how can I define a function with this style?

Asked By: chenkh



Is this what you are looking for?

>>> def abc(a=None,b=None):
...  if a is not None: print a
...  if b is not None: print b
>>> abc("a")
>>> abc("a","b")
>>> abc()
Answered By: Rolf of Saxony

Up to now, I still don’t get an answer expected. Initially, when I saw this way of expression open(name[, mode[, buffering]]), I really want to know what does that mean. It means optional parameters obviously. At that moment, I found it may be a different way(different from normal way like f(a,b,c=None,d='balabala')) to define a function with optional parameters but not only tell us it’s optional parameters. The benefit of this writing can help us use optional parameters but no default value, so I think it’s a more clear and more simple way to define optional parameters.
What I really want to know is about 2 things: 1. if we can define optional parameters using this way(no at present) 2. It will be nice if someone could explain what does the module-level function mean?
I am really appreciated for the above answers and comments! THANKS A LOT

Answered By: chenkh
  1. "if we can define optional parameters using this way(no at present)"

    The square bracket notation not python syntax, it is Backus-Naur form – it is a documentation standard only.

  2. A module-level function is a function defined in a module (including __main__) – this is in contrast to a function defined within a class (a method).

Answered By: cdarke
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.