Python Math libraries - How to?

Terry Reedy tjreedy at udel.edu
Mon Apr 28 23:00:59 EDT 2008


"Gary Herron" <gherron at islandtraining.com> wrote in message 
news:48168670.9040102 at islandtraining.com...
aguirre.adolfo at gmail.com wrote:

You have several ways to import a module, and your choice determines how
you access things.

Method 1:

import math

Then use:  math.pi, math.sqrt, math.sin, math.cos, ...

Method 2:

from math import pi, sqrt

Then use pi, and sqrt.
But other module attributes (like sin, and cos) are not accessible.


Method 3:

from math import *

Then use pi, sqrt, cos, sin, and anything else defined by the module.
(This is sometime  frowned upon, but there's no reason to do so here.)
|
=====================================
|
There are two good reasons for the frown.

One is for the potential conflict between builtin names, imported names 
(from possibly multiple modules), and names defined in the module. 
Builtins and math both have 'pow' functions that I believe are slightly 
different (or maybe once were).  Math and cmath have 13 functions with 
duplicate names but different input and output (2.5).  Importing * from 
both would be disasterous.

The other is that someone not familiar with the imported module(s) will not 
know where a particular name came from when reading the code.  Both 
problems are obvious worse with multiple imports.

Method 4: (my favorite when using multiple names from a module)

import math as m

Then use m.pi, etc.

tjr









More information about the Python-list mailing list