Last active
August 7, 2020 16:23
-
-
Save stestagg/4962d4e86fb586b14138f19af4ae4a02 to your computer and use it in GitHub Desktop.
POC exploring possible syntaxes for the python-ideas thread: Package kwkey and PEP 472 -- Support for indexing with keyword arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding=kw_getitem | |
class Helper: | |
def _getitem_wrapper(self, *a, **kw): | |
a_x = {0: (), 1: a}.get(len(a), (a, )) | |
return self.__getitem__(*a_x, **kw) | |
class ObjWithGetitem(Helper): | |
def __getitem__(self, key=None, foo=None, bar=None): | |
print(f'{key=} {foo=}') | |
def main(): | |
obj = ObjWithGetitem() | |
obj[1] | |
# key=1 foo=None | |
obj[foo=1] | |
# key=None foo=1 | |
obj[1, foo=2] | |
# key=1 foo=2 | |
obj[1, 2] | |
# key=(1, 2) foo=None | |
obj[1, 2, foo=3] | |
# key=(1, 2) foo=3 | |
obj[(1, 2), foo=3] | |
# key=(1, 2) foo=3 | |
obj[(1, 2), 3, foo=4] | |
# key=((1, 2), 3) foo=4 | |
obj[**{'foo': 9}] | |
# key=None foo=9 | |
obj[1, 2, foo=3, xxx=5] | |
# TypeError: __getitem__() got an unexpected keyword argument 'xxx' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from codecs import register, CodecInfo | |
import re | |
def wrap_subs(match): | |
return f'._getitem_wrapper({match.group(1)})' | |
def decode(x): | |
source = bytes(x).decode('utf8') | |
decoded = re.sub(r'\[(.*?)\]', wrap_subs, source) | |
return decoded, len(source) | |
register(lambda n: CodecInfo(None, decode) if n == 'kw_getitem' else None) | |
import example | |
example.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment