Handling 2.7 and 3.0 Versions of Dict

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Sep 2 22:29:59 CEST 2011


En Fri, 02 Sep 2011 13:53:37 -0300, Travis Parks <jehugaleahsa at gmail.com>  
escribió:

> On Sep 2, 12:36 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
> wrote:
>> En Wed, 31 Aug 2011 22:28:09 -0300, Travis Parks  
>> <jehugalea... at gmail.com> escribi :
>>
>> > On Aug 31, 7:37 pm, Gregory Ewing <greg.ew... at canterbury.ac.nz> wrote:
>> >> Ian Kelly wrote:
>> >> > if sys.version_info < (3,):
>> >> >     getDictValues = dict.itervalues
>> >> > else:
>> >> >     getDictValues = dict.values
>>
>> >> > (which is basically what the OP was doing in the first place).
>>
>> > My problem was that I didn't understand the scoping rules. It is still
>> > strange to me that the getValues variable is still in scope outside
>> > the if/else branches.
>>
>> Those if/else are at global scope. An 'if' statement does not introduce  
>> a new scope; so getDictValues, despite being "indented", is defined at  
>> global scope, and may be used anywhere in the module.
>
> Does that mean the rules would be different inside a function?

Yes: a function body *does* create a new scope, as well as the class  
statement. See
http://docs.python.org/reference/executionmodel.html

-- 
Gabriel Genellina




More information about the Python-list mailing list