Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Improve signature of __getitem__ for list and dictΒ #96364

Closed
@sobolevn

Description

@sobolevn

Bug report

Right now both list and dict have incorrrect text signatures of __getitem__.
What is affected?

>>> help(list.__getitem__)
Help on method_descriptor:

__getitem__(...)
    x.__getitem__(y) <==> x[y]

>>> help(dict.__getitem__)
Help on method_descriptor:

__getitem__(...)
    x.__getitem__(y) <==> x[y]

In constrast with __setitem__ and __delitem__:

>>> help(list.__setitem__)
Help on wrapper_descriptor:

__setitem__(self, key, value, /)
    Set self[key] to value.

>>> help(dict.__setitem__)
Help on wrapper_descriptor:

__setitem__(self, key, value, /)
    Set self[key] to value.

>>> help(dict.__delitem__)
Help on wrapper_descriptor:

__delitem__(self, key, /)
    Delete self[key].

It also affects .__text_signature__:

>>> list.__getitem__.__text_signature__
>>> dict.__getitem__.__text_signature__
>>> list.__setitem__.__text_signature__
'($self, key, value, /)'
>>> dict.__setitem__.__text_signature__
'($self, key, value, /)'

And inspect.signature:

>>> inspect.signature(dict.__getitem__)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/sobolev/.pyenv/versions/3.8.9/lib/python3.8/inspect.py", line 3105, in signature
    return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
  File "/Users/sobolev/.pyenv/versions/3.8.9/lib/python3.8/inspect.py", line 2854, in from_callable
    return _signature_from_callable(obj, sigcls=cls,
  File "/Users/sobolev/.pyenv/versions/3.8.9/lib/python3.8/inspect.py", line 2308, in _signature_from_callable
    return _signature_from_builtin(sigcls, obj,
  File "/Users/sobolev/.pyenv/versions/3.8.9/lib/python3.8/inspect.py", line 2119, in _signature_from_builtin
    raise ValueError("no signature found for builtin {!r}".format(func))
ValueError: no signature found for builtin <method '__getitem__' of 'dict' objects>

>>> inspect.signature(dict.__setitem__)
<Signature (self, key, value, /)>

I think that this can be fixed quite easily!
My plan is to modify these two descriptions:

  1. {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, "x.__getitem__(y) <==> x[y]"},
  2. PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]");

With something like typeobject.c has: "__getitem__($self, key, /)\n--\n\nReturn self[key]."

Using clinic here seems impossible / overly-complex.

Should I send a PR for this? πŸ™‚

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions