built-in pow() vs. math.pow()

Roel Schroeven roel at roelschroeven.net
Thu Mar 30 13:22:53 EDT 2023


Andreas Eisele schreef op 30/03/2023 om 11:15:
> I sometimes make use of the fact that the built-in pow() function has an optional third argument for modulo calculation, which is handy when dealing with tasks from number theory, very large numbers, problems from Project Euler, etc. I was unpleasantly surprised that math.pow() does not have this feature, hence "from math import *" overwrites the built-in pow() function with a function that lacks functionality. I am wondering for the rationale of this. Does math.pow() do anything that the built-in version can not do, and if not, why is it even there?
According to the docs, "Unlike the built-in ** operator, math.pow() 
converts both its arguments to type float. Use ** or the built-in pow() 
function for computing exact integer powers." I think that means that 
math.pow() is more meant to work with floats, while the built-in is more 
meant for integers (even though the built-in works with floats just fine).

In any case, I would strongly advocate against "from math import *" (not 
just for math but for any module really). One of the reasons is the 
potential for name conflicts, which is exactly what you experience here.

Either import the things you need explicitly: "from math import sin, 
cos, exp" (for example).
Or a plain import: "import math" combined with "math.sin", "math.cos".
Or use an abbreviation: "import math as m" combined with "m.sin", "m.cos".

-- 
"There is no cause so noble that it will not attract fuggheads."
         -- Larry Niven



More information about the Python-list mailing list