How make your module substitute a python stdlib module.

Thomas Passin list1 at tompassin.net
Tue Dec 27 10:49:45 EST 2022


On 12/27/2022 8:25 AM, Antoon Pardon wrote:
> 
> 
> Op 27/12/2022 om 13:46 schreef Chris Angelico:
>> On Tue, 27 Dec 2022 at 23:28, Antoon Pardon<antoon.pardon at vub.be>  wrote:
>>> 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 :)
> 
> Well it is what will work for the moment. Thanks for the confirmation
> this will indeed work.


What you **should not** do is to make other modules use your code when 
they think they are using the standard library.  Raymond Chen in The Old 
New Thing blog often writes about users who want to do a basically 
similar thing. He always asks "What if some other program wants to do 
the same thing?"  One case was when a developer wanted his program's 
icon to force itself to be at the top position in the Windows task bar. 
"What if another program tried this too?"  The two would keep trying to 
displace each other at the top position.

If you set the PYTHONPATH environmental variable, you can put any 
directory you like to be at the start of the module search path after 
the current directory.  Perhaps this would be enough for your use case?


More information about the Python-list mailing list