On Fri, 7 Aug 2020 at 09:26, Kazantcev Andrey <hec...@yandex.ru> wrote:
>
> The problem in this code
>
> lib.py
> ```
> from json import dumps
>
> def some_func():
>     # do something
>     res = dumps(...)
>     # do something
> ```
>
> I wish dump and load themselves could take parameters from somewhere else, 
> and that was the standard behaviour.

That's such a general statement, you could probably use it for *any*
function, at some point. Which makes your argument pretty weak, IMO.
And to be honest, the standard Python way of providing that behaviour
is monkeypatching. It feels like a hack because the general view is
that needing to do it is a sign of a badly designed API, is all.

For your example, if wanting to change the format of dumps is an
important feature, lib.py "should" have been designed with a
configuration mechanism that allows users to choose that format. The
fact that it doesn't either implies that the author of lib.py doesn't
want you to do that, or that they didn't think of it. Monkeypatching
allows you to address that limitation, so in that sense it's a
flexible but advanced mechanism, not a hack.

It's not particularly hard (as I'm sure you realise):

def custom_dumps(obj):
    json.dumps(obj, param1=preference1, ...)

old_val = lib.dumps
try:
    lib.some_func()
finally:
    lib.dumps = old_val

That needs an understanding of how lib.py works, and it needs you to
accept the risk of using the library in a way that's not supported,
but it's a perfectly reasonable approach for an unexpected case, IMO.

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

Reply via email to