How make your module substitute a python stdlib module.

Dieter Maurer dieter at handshake.de
Tue Dec 27 13:46:38 EST 2022


Antoon Pardon wrote at 2022-12-27 14:25 +0100:
> ...
>> But a simple "sys.modules['threading'] = QYZlib.threaders" will work.
>> Of course, how *well* this works depends also on how well that module
>> manages to masquerade as the threading module, but I'm sure you've
>> figured that part out :)
>
>Well it is what will work for the moment. Thanks for the confirmation
>this will indeed work.

If you need to change a module in minor ways (e.g. only
provide a custom `thread_ident` function), you can use
a technique called "monkey patching" (which is patching at runtime).

You can usually assign new values to module variables.
Thus, you yould try `threading.thread_ident = <your function>`.

This would affect most uses of the function -- which may not be
a good idea.
Alternatively, you could monkey patch the `logging` module.
Look at its code and find out whether it accesses the function
directly or indirectly via `threading`. In the first case,
you would monkey patch the function, in the second the `threading`
variable.

You could also use `dm.reuse` (a package maintained on PyPI)
to override the method using the function. This way, your
change would be even more localized.


More information about the Python-list mailing list