Question about name scope

Ethan Furman ethan at
Wed Feb 1 12:43:14 EST 2012

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.

If you are using Python 2.x you can do:

     def f(a):
         from sympy import *
         return a(a) + d(a)

Python 3 does not allow * imports in functions, however, so you would 
need to do:

     def f(a):
         from sympy import a,b,c,d,e,f,g,h,i,j,k,l,m
         from sympy import n,o,p,q,r,s,t,u,v,w,x,y,z
         return z(a) / f(a) + o(a)

Obviously, only import the functions you are actually going to use.  ;)


More information about the Python-list mailing list