How do I create an alias for a variable in Python?
Python doesn't copy anything implicity, it only stores references so it will work no matter which environment you're in.
# this creates a list and stores a *reference* to it:
really_really_long_variable_name = []
# this creates another new reference to the *same list*. There's no copy.
alias = really_really_long_variable_name
alias.append('AIB')
print really_really_long_variable_name
You'll get ['AIB']
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.