Easy questions from a python beginner

bart.c bartc at freeuk.com
Mon Jul 12 08:56:38 EDT 2010


"Steven D'Aprano" <steve at REMOVE-THIS-cybersource.com.au> wrote in message 
news:4c3aedd5$0$28647$c3e8da3 at 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.

>> That might explain some of the
>> difficulties of getting Python implementations up to speed.
>
> I'm not quite sure why you say that.

Only that an implementation might be obliged to keep these various tables 
updated during function execution, instead of just at entry and exit.

-- 
Bartc 




More information about the Python-list mailing list