* Rhodri James, on 12.07.2010 22:19:
On Mon, 12 Jul 2010 13:56:38 +0100, bart.c <ba...@freeuk.com> wrote:
"Steven D'Aprano" <st...@remove-this-cybersource.com.au> wrote in
message news:4c3aedd5$0$28647$c3e8...@news.astraweb.com...
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:
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.
So Alf P.S. could be right; x exists, but Python pretends it doesn't
until it's assigned to.
CPython, not Python. And as Steven said, x *doesn't* exist. Allowance is
made by that specific implementation of the interpreter because x
*might* exist, but in this particular case it doesn't and a more dynamic
implementation might choose not to reserve a slot just in case. x is
created until it's actually used.
You are conflating existence with space allocation.
It's up to the implementation whether to allocate memory for the variable's
reference in any particular case where that memory isn't strictly required. This
is known as "optimization". Optimization depends on the implementation.
Existence of a variable means, among other things, that
* You can use the value, with guaranteed effect (either unassigned exception
or you get a proper value): in particular, you won't be accessing a global
if you're using the name of a local declared by a later assignment.
* You can assign to it.
How the Python implementation implements that is an implementation detail.
In short, how CPython does things is completely irrelevant to the language's
semantics, so you're conflating things here.
Cheers & hth.,
- Alf
--
blog at <url: http://alfps.wordpress.com>
--
http://mail.python.org/mailman/listinfo/python-list