'Python create functions / classes with variables at don't need to be passed in and have default values
I often use **kwargs when I am creating a function, and then (in the event the user does not pass in a variable) I set a default value with a try and except statement like this:
def function(**kwargs):
# Set a default value for 'start_date' if no value passed into the function
try: start_date = kwargs['start_date']
except KeyError: start_date = '2022-01-01'
I am pretty convinced this is not best practice. For example when using Pandas DataFrames if a variable is not specified a default value is used.
Eg:
df.drop(['column_a'], inplace=True)
If 'inplace' is not specified it defaults to False. How can i reproduce this?
Solution 1:[1]
Instead of using **kwargs you can provide default arguments, which is what they are intended for, which will allow optional parameters
def function(start_date='2022-01-01'):
print(start_date)
>>> function('2022-04-19') # arg
2022-04-19
>>> function(start_date='2022-02-04') # kwarg
2022-02-04
>>> function() # default value
2022-01-01
with the other advantage being implicit validation of arguments which **kwargs would otherwise happily accept
>>> function(wrong=10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function() got an unexpected keyword argument 'wrong'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
