[Python-ideas] Interrogate alternate namespace keyword and concept

ilya ilya.nikokoshev at gmail.com
Fri Aug 14 11:35:55 CEST 2009


Sorry, it's actually even easier; interrogate() is a one-liner:

class Test:
   '''Class to be interrogated.'''
   def __init__(self, value):
       self.value = value

test = Test(10)

def interrogate(what, how):
   exec(how, what.__dict__)

# interrogate test: value += 5
interrogate(test, 'value += 5')

# interrogate test: print(value)
interrogate(test, 'print(value)')


On Fri, Aug 14, 2009 at 1:25 PM, ilya<ilya.nikokoshev at gmail.com> wrote:
> Even if for some reason you needed a statement similar to Pascal's
> "with" (and no, I don't know any example where this could be useful
> since you'll lose access to anything other then the class), you could
> implement it with existing syntax:
>
> class Test:
>    '''Class to be interrogated.'''
>    def __init__(self, value):
>        self.value = value
>
> test = Test(10)
>
> class getattrs(dict):
>    '''An auxiliary class.'''
>    def __init__(self, instance):
>        self.instance = instance
>    def __getitem__(self, name):
>        return getattr(self.instance, name)
>    def __setitem__(self, name, value):
>        return setattr(self.instance, name, value)
>
> # interrogate test: value += 5
> exec('value += 5', getattrs(test))
>
> print(test.value)
> # prints 15.
>
>
> On Fri, Aug 14, 2009 at 12:11 PM, Nick Coghlan<ncoghlan at gmail.com> wrote:
>> Steven D'Aprano wrote:
>>> I don't think there are any problems with a Pascal-style 'with'
>>> statement that couldn't be overcome, but I don't think the benefit is
>>> great enough to create a new keyword for it. Can you explain in more
>>> detail why this proposed feature is useful?
>>
>> Also, if you just want to be able to chain multiple namespaces together,
>> you can do that by implementing an appropriate class with a custom
>> __getattr__ method.
>>
>> Cheers,
>> Nick.
>>
>> --
>> Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
>> ---------------------------------------------------------------
>> _______________________________________________
>> Python-ideas mailing list
>> Python-ideas at python.org
>> http://mail.python.org/mailman/listinfo/python-ideas
>>
>



More information about the Python-ideas mailing list