Search code examples
pythonclassfunctional-programmingdataflowoz

Python 2.7 - How to assign a Class attribute (pointer?) to a variable (Need that to create Oz-esque Dataflow Variables)


Is it even possible?

The idea is that i want to have a special variable, that does some processing when assigning or getting its values. I also want it to look like a regular variable, so the dot notation is a problem here.

I know this is not really explicit, but that's what I need in order to try to replicate the Oz-esque Dataflow Variables.

If something like these style of dataflow variables was already implemented in a python library, please let me know.

Example:

class Promise(object):

    def __init__(self):
        self._value = 'defalt_value'

    @property
    def value(self):
        #some processing/logic here
        return self._value

    @value.setter
    def value(self, value):
        #some processing/logic here
        self._value = value

my_promise_obj = Promise()
my_promise = my_promise_obj.value

my_promise = 'Please, set my_promise_obj.value to this string'

print ('Object`s Value:                  ' + my_promise_obj.value)
print ('My Variable`s value:             ' + my_promise)
print ('Has I changed the class attr?:   ' + str(my_promise == my_promise_obj))

Solution

  • This syntax could not work in Python for that purpose:

    my_promise = 'Please, set my_promise_obj.value to this string'
    

    the reason is that it reassigns the global/local name to point the said string; you cannot hook that assignment; and it does not even consult the object pointed to by my_promise before the assignment.

    However there is plenty to choose from; most obvious are syntaxes like

    • an object with set method:

      my_promise.set('Please, set my_promise_obj.value to this string')
      
    • a method, closure, or any object with __call__ method:

      my_promise('Please, set my_promise_obj.value to this string')
      
    • an object with a data descriptor:

      my_promise.value = 'Please, set my_promise_obj.value to this string'
      

    or something utterly crazy like (just some examples of multitude of possibilities):

    • an object with __iadd__:

      my_promise += 'Please, set my_promise_obj.value to this string'
      
    • an object with __xor__:

      my_promise ^ 'Please, set my_promise_obj.value to this string'
      
    • an object with __rrshift__:

      'Please, set my_promise_obj.value to this string' >> my_promise
      

    could be overridden to set the value.