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.

--
"You can fool some of the people all the time, and all of the people some
of the time, but you cannot fool all of the people all of the time."
        -- Abraham Lincoln
"You can fool too many of the people too much of the time."
        -- James Thurber

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to