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.

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to