How make your module substitute a python stdlib module.

Chris Angelico rosuav at gmail.com
Tue Dec 27 07:46:09 EST 2022


On Tue, 27 Dec 2022 at 23:28, Antoon Pardon <antoon.pardon at vub.be> wrote:
>
>
>
> Op 27/12/2022 om 13:09 schreef Chris Angelico:
> > On Tue, 27 Dec 2022 at 23:06, Antoon Pardon<antoon.pardon at vub.be>  wrote:
> >>> How do you intend to distinguish one from the other? How should the
> >>> logging module know which threading module to use?
> >> That is my question! How can I get the logging module to use my module.I was hoping the logging module would allow some kind of dependency
> >> injection, so you can tell it what threading module to use. An other
> >> option might be to manipulate sys.modules. -- Antoon Pardon
> > But presumably you want OTHER modules to continue using the vanilla
> > threading module? This is likely to end up somewhat hacky. Yes, you
> > can manipulate sys.modules, but there's only one threading module at a
> > time, so you need a way to distinguish between modules that should use
> > the changed one and modules that shouldn't.
>
> But don't these caveats also apply with your original answer of having a
> local threading.py file?
>
> At the moment I am happy with a solution that once the programmer has
> imported from QYZlib.threaders that module will used as the threading
> module.
>

Oh! If that's all you need, then yes, a simple patch of sys.modules
will work. You'll have to make sure you get your module imported
before anything else pulls up the vanilla one, though. Otherwise, your
only option is to keep the existing module object and monkeypatch it
with whatever changes you need.

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 :)

ChrisA


More information about the Python-list mailing list