Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to implement global computed property in Python?

In Swift we can do the following, at any scope (including inside another function):

var X:Int = 3
var twiceX:Int{
    return 2*X
}
print(twiceX) //6

This means we can call a getter function without using the "()" syntax. Any function that takes no argument and return one value can also be implemented as a computer property. Additionally, it is also possible to provide a setter function.

I see that it is possible to make computed properties that belong to classes, using @property declarator, but I see no way to make this a global one. I would expect anything possible at class scope, should be possible at global scope.

Are there global computed properties in Python?

Remarks: I understand that it is mostly a synthetic sugar, that eliminates one pair of ‘()’ every call. However, there are cases where a property is more intuitive than a function. An example is:

queue = [1,4,7]
def current():
    return queue[0]

This is used for the same reason that computed properties is seen in classes: as a presentation of a property, without storing the same information twice.

like image 629
user3468762 Avatar asked Oct 24 '25 17:10

user3468762


1 Answers

No. Variable lookup and attribute lookup are completely separate mechanisms in Python. What is possible in one is not necessarily possible in the other, and in this case, there is no equivalent of property for variables.

like image 50
user2357112 supports Monica Avatar answered Oct 26 '25 06:10

user2357112 supports Monica