Is there a way to create an alias for a value that I want to calculate multiple times, without writing out the same math multiple times

I’ll keep this simple. Consider the following.

a = 1
b = 1
c = a + b
print(c)
# prints 2
a = 2
print(c)
# still prints 2, because that's how variables work

Is there something that looks clean, doesn’t waste RAM, and works like the following?

a = 1
b = 1
alias c = a + b
print(c)
# prints 2
a = 2
print(c)
# prints 3

or…

a = 1
b = 1
with a + b as c:
    print(c)  # prints 2
    a = 2
    print(c)  # prints 3

In other words, can you alias something like a + b?
I am aware that, aside from readability, this is useless, but readability counts!
I also tried the example with with, but got AttributeError: __enter__.

For simple statements, use Lambda functions

c = lambda: a + b
print(c())

The short answer is No. There is nothing like that in Python.

Do you know of any similar features in other programming languages?

The slightly longer answer is that you can almost simulate something not
too far away from your “alias” feature.

As Laurie suggested, you could use a lambda function.

Another alternative is that if your a, b, c are attributes of an object,
you can make c a property:

class C:
    def __init__(self):
        self.a = 1
        self.b = 1
    @property
    def c(self):
        return self.a + self.b

obj = C()
obj.c  # returns 2
obj.a = 99
obj.c  # returns 100
1 Like

Thank you all.

Yeah. I did forget about those. But don’t they use RAM? You store them in variables after all.

I do not, but I would expect that, in a language all about readability,
there would be something like this.

In Python, everything is stored in memory, regardless if it’s assigned to a variable or not, whether it’s a number, lambda function or some other new language construct to store expressions.

You’ll find that even 100,000 lambda functions in an array is insignificant compared to a single Chrome tab

Sure. But so do ordinary functions. At least a lambda will be garbage
collected when the variable referencing it goes out of scope.

Cheers,
Cameron Simpson cs@cskk.id.au