On Fri., 13 Sep. 2019, 7:21 am Steven D'Aprano, <st...@pearwood.info> wrote:

> On Wed, Sep 11, 2019 at 09:34:07AM -0400, Daniel Holth wrote:
>
> > I didn't realize you could override __builtins__.str. That's interesting.
>
> Don't touch __builtins__ that's a CPython implementation detail. The
> public API is to ``import builtins`` and use that.
>
> This override technique is called monkey-patching, it's permitted but
> considered a fairly dubious thing to do in production code, since it
> risks breaking other libraries or even parts of your own code which
> relies on str(b'') working.
>
> It may be better to isolate the monkey-patch to the module (hopefully
> there is only one!) that needs it, by a simple global that shadows the
> built-in:
>
> import builtins
> def str(obj):
>     assert not isinstance(obj, bytes)
>     return builtins.str(obj)
>
> instead of putting it into builtins itself.
>

In a lot of cases like this, the problems aren't with directly calling
str(), but calling third party APIs that indirectly call str().

One nice thing a debugging str() monkey patch can do that the -bb command
line switch can't is be selective in when it fails, by inspecting the frame
stack for the modules of interest before throwing an exception.

Cheers,
Nick.



>
_______________________________________________
Python-Dev mailing list -- python-dev@python.org
To unsubscribe send an email to python-dev-le...@python.org
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at 
https://mail.python.org/archives/list/python-dev@python.org/message/PC6UI6RSTGLWBRVOLII7KFDGJLD56SNU/

Reply via email to