pytoolz / toolz

A functional standard library for Python.
http://toolz.readthedocs.org/
Other
4.71k stars 263 forks source link

dicttoolz and factory #511

Closed bkmi closed 3 years ago

bkmi commented 3 years ago

Dear toolz,

I have been reading the source code of dicttoolz and I cannot understand what the purpose of sending this factory around is (as a result of _get_factory(func, kwargs). Could you please explain it to me?

Clearly it protects against calling a function with bad kwargs, but why is it often instantiated in deeper calls. The valmap call in merge_with for example. Isn't it guaranteed to just be type dict? Why not just instantiate a dict?

Thank you, Ben

groutr commented 3 years ago

@bkmi dicttoolz is designed to work with any class that implements the Mapping (for inputs) and MutableMapping (for factory) interface (https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping). dict just happens to be the most common mutable mapping.

If you were to implement a subclass of dict or even your own mutuable mapping type, you could preserve that type thru toolz. One example might be if you were using Counter classes (from collections) which have some methods/behaviors beyond regular dictionaries. Passing the factory=Counter ensures that the return you get from dicttoolz are Counter objects instead of dict objects. This is also useful if your inputs aren't dict object either, but custom objects that implement Mapping interfaces.

bkmi commented 3 years ago

This is very well explained, thank you.