pythonmethodsequals-operator

Is there a function in Python that does the same thing as the equals operator


Due to my current understanding of Python's syntax, I have run into an issue where I need to set a variable to a value but without using any operators. I have to use functions.

Consider this senario

class Senario:
    x: str = ''
    y: str = ''
    
    set_global_variable(self, set_variable, val: str)
        # some verification code and modifications
        set_variable(val)

    set_x(self, val: str)
        self.set_global_variable(setX, val)

    set_x(self, val: str)
        self.set_global_variable(lambda new_x: self.x = new_x, val)

The benefit of setting variables like this is that adding a new variable doesn't require copying and pasting a bunch of verification code for the new setter method. It is more modular. The problem is that such a program doesn't run because lambdas can't use operators.

The error is self.set_global_variable(lambda new_x: self.x --> = <-- new_x, val)

It's not the proper syntax. In order to run a program like this, I need some sort of equals method that does the exact same thing as the = operator. The implementation would work as follows.

set_x(self, val: str)
    self.set_global_variable(lambda new_x: self.x.equals(new_x), val)

Is there a built-in method in Python to do this, if only for strings? If not, can a method be easily written? One that can take a variable as input and set that exact variable to a new value, and not a local copy of it?


Solution

  • The easiest solution may be to use a local function that performs the assignment, as follows:

    def set_x(self, val: str):
        def _set_variable(new_x):
            self.x = new_x
        self.set_global_variable(_set_variable, val)
    

    However, if you want to use a lambda expression, you can try using the setattr built-in function of python, which does what you asked for:

    def set_x(self, val: str):
        self.set_global_variable(lambda new_x: setattr(self, "x", new_x), val)
    

    A more general solution could be to pass the field name to the set_global_variable and use setattr to perform the assignment, as follows:

    def set_global_variable(self, variable_name, val):
        # some verification code and modifications
        setattr(self, variable_name, val)
    
    def set_x(self, val: str):
        set_global_variable("x", val)