Description
Feature or enhancement
Proposal:
Background
The dict.get()
method is a commonly used feature in Python for retrieving values from dictionaries with a fallback option. Currently, it accepts positional arguments for the key and default value. However, allowing a keyword argument for the default value could enhance code readability and align with Python's philosophy of explicit naming.
Current Behavior
Consider the following code:
my_dict = {"a": 1, "b": 2, "c": 3}
print(my_dict.get("b", "Not found"))
This works as expected. However, when attempting to use a keyword argument:
print(my_dict.get("b", default="Not found"))
It raises a TypeError
:
Traceback (most recent call last):
File "/path/to/script.py", line 3, in <module>
print(my_dict.get("b", default="Not found"))
TypeError: dict.get() takes no keyword arguments
Proposed Enhancement
Allow the use of the default
keyword argument in the dict.get()
method. This would make the code more explicit and easier to read, especially in complex expressions or when the default value is a long expression.
Proposed syntax:
my_dict.get("key", default="default_value")
Rationale
-
Readability: This change aligns with PEP 20 (The Zen of Python), specifically the principle "Explicit is better than implicit." Using a keyword argument makes the intention clearer, especially when the default value is complex or when the method call is part of a larger expression.
-
Consistency: Many Python built-in functions and methods allow both positional and keyword arguments for optional parameters (e.g.,
sorted(iterable, key=None, reverse=False)
). This change would bringdict.get()
in line with this common pattern. -
Backwards Compatibility: This change would be backwards compatible, as it only adds functionality without altering existing behavior.
-
Code Style: It adheres to PEP 8 guidelines for function calls, allowing for more readable code when line length is a concern.
Implementation Considerations
- The current positional argument for the default value should still be supported for backwards compatibility.
- The keyword argument should take precedence if both are provided, with a potential deprecation warning for using both simultaneously.
Conclusion
Introducing a default
keyword argument to dict.get()
would improve code readability and align with Python's design principles. It represents a small but meaningful enhancement to one of Python's most frequently used methods.
Has this already been discussed elsewhere?
This is a minor feature, which does not need previous discussion elsewhere
Links to previous discussion of this feature:
No response