Question about name scope

Mel Wilson mwilson at the-wire.com
Wed Feb 1 19:47:57 CET 2012


Dave Angel wrote:

> 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:
> olive.py:2: SyntaxWarning: import * only allowed at module level
>    def f(a):

I guess they want local symbols in functions to be pre-compiled.  Similar to 
the way you can't usefully update the dict returned by locals().  Strangely, 
I notice that

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(x):
...   exec x
...   exec 'print a'
... 
>>> f('a=4')
4
>>> 

works, but I really cannot explain why.

	Mel.




More information about the Python-list mailing list