Reputation: 53
In Python, there are a few different ways to set default keyword arguments in a function. The ways I know of are:
def default(para_1: str = "this is", para_2: str = "an example"):
print(para_1, para_2)
and:
def keyword(**kwargs):
para_1 = kwargs.get("para_1", "this is")
para_2 = kwargs.get("para_2", "an example")
print(para_1, para_2)
Both of these functions can be called like so:
default(para_1="this is", para_2="another example")
keyword(para_1="this is", para_2="another example")
to achieve the same effect. The only difference I know of between the two methods are when using mutable default values, where default parameters would need to be written as:
def mutable_default(para_1: dict = None):
if para_1 is None:
para_1 = {}
while the kwarg method wouldn't need to be re-structured in the same way, as it is safe with mutable defaults:
def mutable_keyword(**kwargs):
para_1 = kwargs.get("para_1", {})
Is there a preferred method between the two?
Upvotes: 2
Views: 4888
Reputation: 184230
Yes. Use real arguments as much as possible, because they will be shown in the function's help()
. Seeing that a function has a signature (**kwargs)
tells you nothing about what arguments it accepts. Seeing the signature (search_term, whole_word=False, case_sensitive=True)
is much more valuable.
Using good names is a form of documentation and reduces the need to write other documentation (and the likelihood it will go out of date due to changes in the code).
Upvotes: 8