So, in short, your idea is to allow "=" signs inside `[]` get notation to be translated to dicts on the call, in the same way comma separated values are translated to tuples? I see no backwards syntax incompatibility in that, and the tuple-translation is indeed quite a helper in many cases. The use cases for this even in existing popular libraries, such as Pandas, is very clear. I am full +1 for this proposal - yes, it can help. I hope people can argue here and see the benefits without a lot of bike-shedding - and if it turns out good, I offer to help formalizing a proposal for that. On Fri, 4 Oct 2019 at 16:58, Caleb Donovick <donovick@cs.stanford.edu> wrote:
While there is no restriction on passing dicts to getitem. Doing so tends to be a bit ugly. I have two main use cases in mind for this syntax.
The first and perhaps the most obvious, is doing relational queries. ``` where_x_1 = db[x=1] ``` is more beautiful than ``` where_x_1 = db[dict(x=1)] where_x_1 = db[{'x': 1}] # or by abusing slices where_x_1 = db['x':1] # or in the style of Pandas where_x_1 = db[db['x'] == 1] ```
Beyond relational queries my own personal use case is a shorthand for dataclasses / protocols. ``` foo: ProtoRecord[x=int, y=int] = DataRecord[x=int, y=int](0, 1) ``` where `DataRecord[field0=T0, ..., fieldk=Tk]` generates ``` @dataclass class Record: field0: T0 ... fieldk: Tk ``` and `ProtoRecord[field0=T0, ..., fieldk=Tk]` generates a similar protocol.
Allowing key value pairs in geitem need not change the interface of getitem. All the key value pairs could be collected as a dict and passed to getitem as the index. Similar to how the all the positional arguments are gather into a single tuple. ``` class Foo: def __getitem__(self, idx): print(idx)
f = Foo() f[x=1, y=2] # {'x': 1, 'y': 2} ``` This would make any legacy code using normal dicts as keys (I don't know how prevalent that is) automatically work with the new syntax.
There doesn't necessarily need to be support for mixing of tuple based indexing and keyword indexing. i.e. ``` obj[0, x=1] # SyntaxError ```
I don't really know anything about parsers but I think the grammar could be extended without issue with the following rule: ``` subscriptlist: ... | kwargsubscript (',' kwargsubscript )* [','] kwargsubscript: NAME '=' test ``` if `NAME '=' test` would result in ambiguity similar to argument it could be `test '=' test` with a block in ast.c
- Caleb Donovick _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-leave@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/EUGDRT... Code of Conduct: http://python.org/psf/codeofconduct/