Easy questions from a python beginner
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Mon Jul 12 06:26:29 EDT 2010
On Mon, 12 Jul 2010 09:48:04 +0100, bart.c wrote:
> That's interesting. So in Python, you can't tell what local variables a
> function has just by looking at it's code:
In the presence of "exec", you can't really tell *anything*.
>>> def f(s):
... exec s
... print locals()
...
>>> f("x = 2;y = None")
{'y': None, 'x': 2, 's': 'x = 2;y = None'}
> def foo(day):
> if day=="Tuesday":
> x=0
> print ("Locals:",locals())
>
> #foo("Monday")
>
> Does foo() have 1 or 2 locals?
That's easy for CPython: it prepares two slots for variables, but only
creates one:
>>> foo("Monday")
('Locals:', {'day': 'Monday'})
>>> foo.func_code.co_varnames
('day', 'x')
>>> foo.func_code.co_nlocals
2
So, the question is, is x a local variable or not? It's not in locals,
but the function clearly knows that it could be.
> That might explain some of the
> difficulties of getting Python implementations up to speed.
I'm not quite sure why you say that.
--
Steven
More information about the Python-list
mailing list