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.
The keyword 'as' is used to create an alias in python.
How can I alias a function in Python? from __future__ import print_function at the top of your file will make Python 2 use the Python 3 version of print , so that you can do debug = print .
Type aliases are user-specified types which may be as complex as any type hint, and are specified with a simple variable assignment on a module top level. This PEP formalizes a way to explicitly declare an assignment as a type alias.
A variable alias (also called a ghost) is a copy of a stock, flow, or converter that lets you use the original variable elsewhere in your model. The variable alias isn't a new, separate variable. Instead, it's a shortcut to the original variable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With