surprise: dict.get's default is a positional only parameter!
Chris Angelico
rosuav at gmail.com
Sat Sep 12 02:49:09 EDT 2020
On Sat, Sep 12, 2020 at 4:18 PM Cameron Simpson <cs at cskk.id.au> wrote:
>
> Normally, if one writes a method like this:
>
> def get(self, k, default=None):
>
> one can call it as foo.get('x',2) or as foo('x',default=2).
>
> But not with dict.get. I'm amazed I've never tripped over this before.
> (Yes, I appreciate that dict is a builtin class written in C.)
>
Yeah. In recent Python versions, you can use this functionality in
your own code too. The docs for the get method say:
Help on built-in function get:
get(key, default=None, /) method of builtins.dict instance
Return the value for key if key is in the dictionary, else default.
The slash means that everything previous to that parameter is
positional-only. Comes in handy, occasionally:
>>> def spam(x, y, /, **kw):
... print(x, y, kw)
...
>>> spam(1, 2, x=3, y=4)
1 2 {'x': 3, 'y': 4}
ChrisA
More information about the Python-list
mailing list