[Tutor] operator and function call

Tim Peters tutor@python.org
Tue, 22 May 2001 06:28:36 -0400


[Praveen Pathiyil]
> What is the rationale in implementing some functionalities both as
> an operator and as a function call ?

It varies from case to case.

> E.g: 2 raised to the power of 3 can be computed as
> 2 ** 3 and as pow(2,3)

2**3 is preferred.  The primary use for the pow() function is the
three-argument form pow(a, b, c), which computes (a**b) % c but very much
faster than the latter when b is large and c is small.  "modular pow" is an
important operation in, for example, number theory and cryptography.

You're also missing math.pow(), which is yet a third version of pow.  It's
not like either of the others, but the difference is subtle (math.pow() does
exactly whatever the function named "pow" in your local C library does).

> Similarly a - b and operator.sub(a,b)

Different case entirely.  a-b is preferred.  The operator module is rarely
used and you can safely ignore it for the rest of your life <wink>.  If you
ever *wanted* to, say, pass a two-argument subtraction function as an
argument to another routine, then

    another_routine(a-b)

would pass the *result* of a-b, but

    another_routine(operator.sub)

does the right thing and runs faster than the equivalent

    def sub(a, b):
        return a - b

    another_routine(sub)

This is rarely important; the operator module exists for the benefit of the
few applications where it is important.

> Any specific reasons for such an approach ?

There are always reasons, but not always compelling reasons.  The answers
aren't usually exciting <wink>.