Search code examples
pythonvariablesalias

How do I create an alias for a variable in Python?


Normal way:

class A:
    def __init__(self):
        self.a.b.c = 10

    def another_method(self):
        self.a.b.c = self.a.b.c * 10

Aliased approach:

class A:
    def __init__(self):
        self.a.b.c = 10         
        alias self.aliased = self.a.b.c  # Creates an alias 

    def another_method(self):
        self.aliased = self.aliased * 10  # Updates value of self.a.b.c

How does one accomplish aliasing in Python? The reason I want to do this is to reduce cluttering due to long variable names. It's a multi threaded environment, so simply copying to a local variable will not work.


Solution

  • The solution to this is to use getter and setter methods - fortunately Python has the property() builtin to hide the ugliness of this:

    class A:
        def __init__(self):
            self.a.b.c = 10
    
        @property
        def aliased(self):
            return self.a.b.c
    
        @aliased.setter
        def aliased(self, value):
            self.a.b.c = value
    
        def another_method(self):
            self.aliased *= 10  # Updates value of self.a.b.c
    

    Generally, deeply nested attributes like self.a.b.c are a sign of bad design - you generally don't want classes to have to know about objects that are 3 relationships away - it means that changes to a given item can cause problems throughout your code base. It's a better idea to try and make each class deal with the classes around it, and no further.