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?
2 Answers
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()
>>>
7 Comments
cdarke
Not a good idea to equate
None with False in this case. What if a or b had the value 0 (zero) or "" (empty string)?cdarke
!= has its dangers as well. Test for not None might be better as if not a is None:Rolf of Saxony
@cdarke "comparisons to singletons like None should always be done with is or is not, never the equality operators." Thank you, we live and learn.
flakes
By default python uses a memory reference to check equality of
Object instances (different than primitives). However, operators in python can be overwritten such as __eq__. This means that a and b are not guaranteed to be a simple reference check. It could possibly try to access a field within the None instance and then error out. The is keyword on the other hand will only ever do a reference test- removing the potential error. (it will also perform quicker as a result of the simpler operation) |
"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.
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).
def f(a=None, b=None)