On Sun, Jun 05, 2022 at 09:11:41PM -0000, Steve Jorgensen wrote:

> m = {'a': 123, 'b': 456, 'c': 789}
> m.except(('a', 'c'))  # {'b': 456}
> m.only(('b', 'c'))  # {'b': 456, 'c': 789}
> m.values_at(('a', 'b'))  # [123, 456]

Maybe I'm a bit slow because I haven't had my morning coffee yet, but I 
had to read those three times before I could work out what they actually 
do. Also because I got thrown by the use of the keyword `except`, and 
thought initially that this was related to try...except.

And lastly because you say that these are extremely common, but I've 
never used these operations in 20+ years. Or at least not often enough 
to remember using them, or wishing that they were standard methods.

These operations are so simple that it is easier to follow the code than 
to work out the meaning of the method from the name:

    # Return a new dict from an old dict with all but a set of keys.
    new = {key:value for key, value in old.items() if key not in exclusions}

    # Return a new dict from an old dict with only the included keys.
    new = {key:value for key, value in old.items() if key in inclusions}

    # Same as above, but only those matching the included values.
    new = {key:value for key, value in old.items() if value in inclusions}

    # Return the values (as a set) of a subset of keys.
    values = {value for key, value in old.items() if key in inclusions}

    # Use a list instead, and exclude keys.
    values = [value for key, value in old.items() if key not in exclusions]

    # Same, but use a predicate function.
    values = [value for key, value in old.items() if not predicate(key)]

    # How about a list of values matching *either* a blacklist of keys 
    # and a whitelist of values, *or* a predicate function on both?
    values = [value for key, value in old.items()
              if (key not in blacklist and value in whitelist)
              or predicate(key, value)]


Comprehensions are great!

Yes, they take a few extra characters to write, but code is written much 
more than it is read. Once we have learned comprehensions, it is much
easier to read a simple comprehension than to try to decipher a short 
name like "only". Only what? Only those that match a given list of keys, 
or values, or a predicate function, or something else?


-- 
Steve
_______________________________________________
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/766W3IAURXW3FRTJNH2657XHIXYL7LHY/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to