[Python-ideas] operator.call / operator.__call__
Terry Reedy
tjreedy at udel.edu
Thu Oct 30 19:38:16 CET 2014
On 10/30/2014 4:07 AM, Antony Lee wrote:
> I have two use cases below. Yes, it is true that just defining the
> "call" function myself would only take me two lines, but on the other
> hand the same is true for most functions in the operator module...
The primary intended use of operator.op functions is to be passed as
arguments since operators themselves cannot be. By exposing C-coded
wrappers, they make this possible more efficiently than would be the
case with Python wrappers. There never seemed to be a need to pass
'apply' itself as an argument, and the newer of f(*args, **kwds) made
its direct use unneeded. Hence it was deleted.
The signature of apply is apply(func, arg[, keywords]). The arguments
are not unpacked just to be repacked and unpacked again, as would happen
with your renamed version of apply.
> - Sometimes, depending on a switch, you want either to call a function
> directly, or to pass it to a specialized "caller", e.g.
Then either call it directly or pass it to a specialized caller.
> def run_in_thread(func, *args, **kwargs):
> Thread(target=func, args=args, kwargs=kwargs).start()
In its use below, this would be more efficient as
def run_in_thread(func, args, kwargs):
> def run_here_or_in_thread(in_thread, func, *args, **kwargs):
> (run_in_thread if in_thread else operator.call)(func, *args, **kwargs)
With the altered sig, this can be written
(run_in_thread(func, args, kwargs) if in_thread else
func(*args, **kwargs))
--
Terry Jan Reedy
More information about the Python-ideas
mailing list