parse
parse copied to clipboard
Iterating over named results
This started as me writing bad code in a slide, so feel free to ignore ;-)
So, I wrote this:
x, y = parse('{x:d}x{y:d}', '100x200')
And of course that doesn't work. It does work using {:d}x{:d}
... would it be possible for Result.__getitem__
to iterate over named matches if there are no fixed matches?
It just feels strange that giving a name to the matches changes the iterating behaviour.
Since the named values are stored in a dict called named
, a workaround for your case could be
x, y = parse('{x:d}x{y:d}', '100x200').named.values()
Regarding the suggested change in behaviour, IMO would be a bit too magical for this convenience feature. It's hard to tell what kind of elements should be returned from the iterator, especially if you start mixing named and unnamed arguments,. What would you expect to have returned from, say, list(parse('{x}x{}x{z}', '50x100x200'))
? I could argue for any of the following, but all of them are surprising in their own way:
-
['100']
(existing behaviour) -
['50', '100', '200']
-
['x', '100', 'z']
-
[('x', '50'), '100', ('z', '200')]
-
[('x', '50'), (parse.NO_NAME, '100'), ('z', '200')]
Sorry, too magical.
parse.Result
is only iterable because it implements __getitem__
in a way that satisfies the "old-school" iterator protocol. For the iteration to switch behaviors depending on presence of named fields or not doesn't seem sensible.