chenkh
chenkh

Reputation: 69

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?

Upvotes: 3

Views: 2388

Answers (2)

cdarke
cdarke

Reputation: 44354

  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).

Upvotes: 1

Rolf of Saxony
Rolf of Saxony

Reputation: 22443

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")
a
>>> abc("a","b")
a
b
>>> abc()
>>> 

Upvotes: 2

Related Questions