Marco-Sulla / python-frozendict

A simple immutable dictionary for Python
https://github.com/Marco-Sulla/python-frozendict
GNU Lesser General Public License v3.0
133 stars 16 forks source link

[FEATURE] keys_of() method #13

Open Marco-Sulla opened 4 years ago

Marco-Sulla commented 4 years ago

keys_of(value, deep=False) method should return a generator, that checks in frozendict values if they are equal to value. If yes, the keys are yielded.

If deep=True, value does not match the current value and it's a iterable, that is not an iterator-like or a set-like, the function will search recursively for the value in the iterable and any sub-iterable. If the iterable is a sequence, the indexes of the value is yielded. If it's a map-like, the keys are yielded.

Example:

fd = frozendict({1: 2, 7:2, 2: {5: 2, 7: 2, 0: [2, 1]}, 3: [0, 4, 2, 1, 2]})
tuple(fd.keys_of(2))
# (1, 7)

for x in fd.keys_of(2, deep=True)):
    print(tuple(x))
# (1, )
# (7, )
# (2, 5)
# (2, 7)
# (2, 0, 0)
# (3, 2)
# (3, 4)

See also #14

lurch commented 4 years ago

Are #13, #14 and similar all "feature-creep"? i.e. adding extra functions that you think that Python dictionaries should have? Should frozendict 'just' be a frozen dict-like class with the same API as dict, or are you writing a frozendict++? :stuck_out_tongue_winking_eye:

Marco-Sulla commented 4 years ago

Yes, I think dict should have a keys_of(). It's similar to list.index() and I feel the need of it a couple of times. My hope is that it will be developed also in dict.

frozendict is a map-like object. It can't have the same API of dict, since dict is mutable. But it have all the API that does not change the object. So the APIs can't be ever equal.

Your observation about feature-creep is good. Software and libraries have the tendency of overdoing. See Netscape for example. And the the KISS and YAGNI principles are always valid.

I suppose the questions we have to answer to ourselves when we want to add another feature to our class / library / app are:

  1. Is it something useful?
  2. Is it inherent to the product or is out of scope?
  3. Is it something that can be delegated to another product in a more elegant manner (a third-party module, a subclass...)?

IMHO the answer to these questions, in this case, are yes, inherent, no.

Marco-Sulla commented 4 years ago

Closed per https://github.com/Marco-Sulla/python-frozendict/issues/17

Marco-Sulla commented 1 year ago

Reopening for implementing it also in the C Extension.