Creating a local variable scope.

Lie Ryan lie.1296 at gmail.com
Sun Nov 29 23:11:50 CET 2009


On 11/30/2009 8:12 AM, markolopa wrote:
> Hi,
>
> On 18 Sep, 10:36, "markol... at gmail.com"<markol... at gmail.com>  wrote:
>> On Sep 11, 7:36 pm, Johan Grönqvist<johan.gronqv... at gmail.com>  wrote:
>>> I find several places in my code where I would like tohavea variable
>>> scope that is smaller than the enclosing function/class/module definition.
>>
>> This is one of the single major frustrations I have with Python and an
>> important source of bugs for me. Here is a typical situation
>
> Here is another bug that I just got. Twenty minutes lost to find it...
>
> class ValueColumn(AbstractColumn):
>      def __init__(self, name, header, domain_names):
>          if type(domain_names) != tuple:
>              raise ValueError('a tuple of domain names must be given')
>          for name in domain_names:
>              if type(name) != str:
>                  raise ValueError('a tuple of domain names must be
> given')
>          self.domain_names = domain_names
>          super(ValueColumn, self).__init__(name, header)
>
> The upper class was initialized with the wrong name, because the for
> loop to check
> domain_names used "name" which is also the argument to be passed.
>
> If is an old thread but I am reopening to present real situation where
> this Python
> "feature" bothers me...
>

here is another bug you might have if python have an "even-more-local" 
scope:

while True:
     s = raw_input("enter something: ")
     if s not in ('q', 'quit', 'exit'): break
print s

if the while block has become its own namespace; print s would generate 
NameError.

It is one or the other, you will have problem caused by "namespace too 
small" or "namespace too big". Neither is better than the other, so 
python's two-level name resolution (global and local level) is the 
simplest one, is the better one.



More information about the Python-list mailing list