Creating a local variable scope.

Ethan Furman ethan at stoneleaf.us
Sat Sep 19 23:11:50 CEST 2009


Dave Angel wrote:
> Johan Grönqvist wrote:
>> DiZazzo skrev:
>>
>>> I would do something like this:
>>>
>>>>>> class Namespace(object):
>>>
>>> ...     pass
>>> ...
>>>
>>>>>> n = Namespace()
>>>>>> n.f = 2
>>>>>> n.g = 4
>>>>>> print f
>>>
>>> Traceback (most recent call last):
>>>   File "<stdin>", line 1, in ?
>>> NameError: name 'f' is not defined
>>>
>>>>>> print n.f
>>>
>>> 2
>>
>>
>> I like this solution. This also minimizes the extra code if I would 
>> want to explicitly delete the bindings, as I would only need one line 
>> to delete the Namespace object.
>>
> Even simpler solution for most cases, use longer names.  If the name 
> means something in the local context, and the next context is different, 
> you presumably will use a deliberately different name.  In your earlier 
> example, if you called them row and column, you ought to notice if you 
> used row instead of column in the later "scope".
> 
> One thing people don't notice when they ask the compiler to catch all 
> these types of problems is that there are lots of things the compiler 
> can't check.

Well said.  One of the things I *love* about Python is that it doesn't 
try to do my programming for me.  For the mistakes we inevitably make, 
good test suites are incredibly useful.

Still, and just for fun, the following is at least mildly entertaining 
(but then, I am easily amused :)

class micro_scope(object):
     def __enter__(self):
         return self
     def __exit__(self, type, value, traceback):
         if type is value is traceback is None:
             self.__dict__.clear()

with micro_scope() as m:
     m.this = 'that'
     m.value = 89
     for m.i in range(10):
         do_something_with(m.i)

m.value
#exception raised here, as m.value no longer exists

Don't worry, Steven, I'll never actually use that!  ;-)

~Ethan~



More information about the Python-list mailing list