Passing information between modules

Thomas Passin list1 at tompassin.net
Sun Nov 20 14:33:01 EST 2022


On 11/20/2022 1:50 PM, Roel Schroeven wrote:
> Stefan Ram schreef op 20/11/2022 om 11:39:
>>    The idea is about parameterizing the behavior of a module.
>>    For example, the module "M" may contain functions that contain
>>    "input.read()" to get input and "output.write()" to write
>>    output. Then one would write code like (the following is
>>    not correct Python code, just pseudo code assuming a possible
>>    extended Python where one can assigned to a module before
>>    it's loaded):
>>
>> import sys
>>
>> M.input = sys.stdin
>> M.output = sys.stdout
>> import M
>>
>>    . So now M would use sys.stdin for input and sys.stdout
>>    for output.
> I feel this is a bad idea. This uses global state for customizing local 
> behavior. Yes, maybe you want to customize behavior in one of your 
> modules, or even only in some functions, or maybe in several or even all 
> of your modules. But by changing module "M", you're changing it for 
> *every* user of it, even for standard library modules or third party 
> packages. You can't customize it in different ways in different parts of 
> your code. And it's a kind of spooky action at a distance: the behavior 
> of a module gets changed by another, possibly completely unrelated, 
> module. This has the potential to grossly violate the principle of least 
> surprise.
>>    If someone else would ask this, I'd tell him to use a class:
>>
>> import MM
>> import sys
>>
>> M = MM.moduleclass( input=sys.stdin, output=sys.stdout )
> That is a *much* better solution, and I would even say it's the only 
> acceptable solution.
>>    , but this is another layer of indirection, so it's a bit
>>    more complicated than the direct approach of parameterizing
>>    a module.
> I'm not even sure it's more complicated. It's more explicit, which I like.
> 
> You could have a hybrid approach, like what the random module does. The 
> functions in the random module are actually methods of a global hidden 
> instance of class random.Random; if you want random generators with 
> separate states you can create your own instance(s) of random.Random, or 
> of random.SystemRandom.


As I wrote, it's another case of "what if everyone did this". e.g.:

https://devblogs.microsoft.com/oldnewthing/20050607-00/?p=35413
https://devblogs.microsoft.com/oldnewthing/20101125-00/?p=12203



More information about the Python-list mailing list