-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
remove mutable default values for kwargs (#2668)
This subtle misunderstanding of Python tends to cause confusing bugs. Suppose you have a definition statement like 'def function(keys=[]): ...' This def statement is evaluated once, at import time, to create a function object. It is at this time that '[]' is evaluated, and it is that ONE list object which is retained as the default value for 'keys'. Python doesn't store the expression and re-evaluate it every time the default is needed, it evaluates it once at import time and the resulting value is passed for every call where that arg is not given. To explain this with code, the effect is something like this: default_keys = [] def function(keys=default_keys): ... When function() is called with a value for keys, no problem will be seen. Even when it is called with no value for keys, and we default to that list, you might not see a problem. The problem that tends to happen unpredictably is that the mutable default value is mutated. Those changes are persistent and globally visible to any call of the function which uses the default. Then the default value is non-empty. Or information leaks across calls that shouldn't be leaking. Or the same dict keeps growing forever. To avoid this, we can use a sentinel value such as None, and then check for that value in the body of the function. It is a cheap safeguard against situations that can be very annoying.
- Loading branch information
Showing
5 changed files
with
39 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters