Is it possible to create a variable as a placeholder for 'current' value of a class in python?
Question: Let's say we have a class:

_NOTE: this is a dummy class only._

    
    
    class C(object):
        def __init__(self):
            self.a = -10
            self.b = 5
            self.c = 2
        def modify(self, **kwargs):
            for keyword in kwargs:
                vars(self)[keyword] = kwargs[keyword]
            return(self)
    

And we want to use this modify method to change values in our object:

    
    
    myclass = C()
    myclass = myclass.modify(a=10)
    

But when I want to change the value based on the original one, I have to write
this:

    
    
    myclass = C()
    myclass = myclass.modify(a=myclass.a/10)
    

Or:

    
    
    myclass = myclass.modify(a=abs(myclass.a))
    

My question is, is there a way, to create a global variable in a module, that
I can import and use it as a placeholder for current value, so I can use this
formula:

    
    
    from globvars import current
    
    myclass = C()
    myclass = myclass.modify(
        a=abs(current) % current ** 2,
        b=current//2,
        c=bool(current)
    )
    

First I tried to a create a class, which will store the operation it is taking
and a value, and `modify()` will look first for its variable as a keyword and
then execute the function. Actually it is only working for simple situations
like: `current+10` or `current**2`. But when I realised, I want to use this
`current` for example with an `hsba(current)` (_color converter_) function,
where `current` is pointing to an object stored in an other object, I just
give up, I can't write this to every class I'm going to use..

Is there a solution for this? Maybe it's quite easy, I just can't see it :)

Thanks in advance for replies!


Answer: Your `modify` method could take the name of the attribute to modify, and a
function that takes the current value of the attribute and returns its new
computed value. Then you can do something like:

    
    
    def compute_new_value(current):
        new_value = abs(current) % current ** 2
        return new_value
    
    myclass = C()
    myclass.modify('a', compute_new_value)
    

For simple cases, `lambda` makes it less verbose:

    
    
    myclass.modify('a', lambda cur: cur + 4)
    

And your class:

    
    
    class C(object):
        [...]
        def modify(self, attr_name, func):
            cur_value = getattr(self, attr_name)
            new_value = func(cur_value)
            setattr(self, attr_name, new_value)
    

**Edit** : I may have missed something. Since you're writing `myclass =
myclass.modify...`, should the `modify` method return a _copy_ of the object ?

