Is there a way in Python to pass optional parameters to a function while calling it and in the function definition have some code based on "only if the optional parameter is passed"
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
The Python 2 documentation, 7.6. Function definitions gives you a couple of ways to detect whether a caller supplied an optional parameter.
First, you can use special formal parameter syntax
*
. If the function definition has a formal parameter preceded by a single*
, then Python populates that parameter with any positional parameters that aren't matched by preceding formal parameters (as a tuple). If the function definition has a formal parameter preceded by**
, then Python populates that parameter with any keyword parameters that aren't matched by preceding formal parameters (as a dict). The function's implementation can check the contents of these parameters for any "optional parameters" of the sort you want.For instance, here's a function
opt_fun
which takes two positional parametersx1
andx2
, and looks for another keyword parameter named "optional".Second, you can supply a default parameter value of some value like
None
which a caller would never use. If the parameter has this default value, you know the caller did not specify the parameter. If the parameter has a non-default value, you know it came from the caller.If you want give some default value to a parameter assign value in (). like (x =10). But important is first should compulsory argument then default value.
eg.
(y, x =10)
but
(x=10, y) is wrong
http://docs.python.org/2/tutorial/controlflow.html#default-argument-values
I find this more readable than using
**kwargs
.To determine if an argument was passed at all, I use a custom utility object as the default value:
You can specify a default value for the optional argument with something that would never passed to the function and check it with the
is
operator:then as long as you do not do
func(_NO_DEFAULT)
you can be accurately detect whether the argument was passed or not, and unlike the accepted answer you don't have to worry about side effects of ** notation: