I've written a decorator to go along with Guido's proposed
implementation, to make it easier to write item dunders that
take positional args that can also be specified by keyword.

#-----------------------------------------------
from inspect import signature

def positional_indexing(m):
  def f(self, args, **kwds):
    if isinstance(args, tuple) and len(args) != 1:
      return m(self, *args, **kwds)
    else:
      return m(self, args, **kwds)
  f.__name__ = m.__name__
  f.__signature__ = signature(m)
  return f
#-----------------------------------------------

Usage example:

#-----------------------------------------------
class Test:

  def __init__(self):
    self.data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

  @positional_indexing
  def __getitem__(self, i, j):
    return self.data[i][j]

t = Test()
print(signature(t.__getitem__))
print(t[1, 2])
# Have to fake this for now until we get real keyword index syntax
print(t.__getitem__((), j = 2, i = 1))
#-----------------------------------------------

Output:

(i, j)
6
6

--
Greg
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/I6QP4LN2UEX5YWAI6ZK5S6MAYHQCOYMM/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to