More than once, I’ve heard the criticism of default parameters because they obscure the API.
Criticism of default parameters
The criticism of default parameters is mostly in other languages (static languages, dynamic languages, because of the lack of “method overloading”). The main reasons, I think, are: not syntactically natural and unfriendly to people who look at the code.
For example, in C++ :
Void DoSomething(int a, int b=100); 1. DoSomething(1) 2. DoSomething(1, 1000)Copy the code
Without sufficient context, at first glance, these are two overloaded methods that impose a mental burden.
So in C++, default parameters are rarely used.
How does Python handle this
In Python, the above defects are not immune, or even worse. For example, Python allows you to write code like this:
1. DoSomething(1)
2. DoSomething(1, 1000)
3. DoSomething(1, b=1000)
Copy the code
This is very pit dad, if the parameters are more, more combinations, and even puzzling error. 1 is normal, 2 is bad habit, 3 is good habit.
So, from this point of view, Python seems to be making things worse. So, should we “starve to death without eating for fear of choking”?
The right thing to do
It doesn’t have to be that way. Also, this is an opportunity to demonstrate your skills as an API author.
The first is Python 3 (assuming >= 3.5). Take advantage of the new feature so that the caller can only use the third notation. Such as
def DoSomething(a, *, b=10, c=100, d=1000): Pass calls can either ignore the default: DoSomething (100) or add dot characters: DoSomething (100, b=100, c=11, d=0).Copy the code
Next is Python 2. The solution: Switch to Python 3. Or you assume that the People next to you are highly qualified Python users who are committed to following best practices (what are the odds?). .
By the way, no one, no article, talks about 2 and 3 anymore. Conservative new projects, all Python 3.5 (our new project is 3.6).