Question about name scope

Dave Angel d at
Wed Feb 1 18:36:36 CET 2012

On 02/01/2012 12:11 PM, Olive wrote:
> I am learning python and maybe this is obvious but I have not been able
> to see a solution. What I would like to do is to be able to execute a
> function within the namespace I would have obtained with  from<module>
> import *
> For example if I write:
> def f(a):
> 	return sin(a)+cos(a)
> I could then do:
> from math import *
> f(5)
> But I have polluted my global namespace with all what's defined in
> math. I would like to be able to do something like "from math import *"
> at the f level alone.
> The main reason for this is the sympy module for CAS (computer algebra).
> It reimplement a lot of functions and define all the letters as symbolic
> variables. Writing sympy.<function>  everywhere is inconvenient.
> Importing all the symbols in the global namespace would lead to name
> clash. It would be nice if I could import all the sympy names but for a
> given function only.
> Olive
Start by specifying python version and operating system.

I tried your experiment using Python 2.7 and Linux 11.04

def f(a):
     from math import sin, cos
     return sin(a) + cos(a)

print f(45)

Does what you needed, and neatly.  The only name added to the global 
namspace is f, of type function.

I was a bit surprised that using   from math import * inside the 
function worked, but it generates  a warning: SyntaxWarning: import * only allowed at module level
   def f(a):

I normally avoid any use of the "from XX import *" form, as it pollutes 
the global name space.  The only exception is when a library writer 
documents that this is the "normal" way to interface to it.  In this 
case, he usually defines just a few things that are visible this way)

What I do is put a single import math at the top of my source file, and 
use math.sin, and math.cos where needed.  Occasionally, I'll use 
something like:

      from math import sin,cos

at the top, so I know just which symbols I'm defining.

How about:

import math

def f(a):
     sin = math.sin
     cos = math.cos
     return sin(a) + cos(a)

print f(45)

This lets you explicitly use the sin and cos names inside the function, 
by defining them at entry to the function.



More information about the Python-list mailing list