Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 314
AIB Avatar asked Jun 15 '12 11:06

AIB


People also ask

How do I create an alias in Python?

The keyword 'as' is used to create an alias in python.

How do you assign an alias to a function 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 .

What is alias type in Python?

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.

What is a variable 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.


1 Answers

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.

like image 105
Gareth Latty Avatar answered Sep 22 '22 15:09

Gareth Latty