Dynamic variable always linked to a method in Python Dynamic variable always linked to a method in Python tkinter tkinter

Dynamic variable always linked to a method in Python


If you just want a shorthand,

X = root.winfo_widthprint X()


The problem is that, although Python is really dynamic, there are a few things that always do exactly the same thing that can't be changed.

One is simple assignment:

x = ...some complex expression...

This always does the same thing: it evaluates "some complex expression", and then x is changed so that it is now a reference to the result of the expression.

The other is variable evaluation:

x

Simply using a single variable never invokes any code or methods or anything -- in the expression where you use x, x is simply "replaced" by whatever it is referring to.

So doing exactly what you want isn't possible, there's no place to add something dynamic. Method lookup is an obvious alternative:

x.y

Here, you could implement x.getattr to return the thing you need (too tricky), or you could give x a property method y (as in the other answers).

The other thing is that x could refer to a mutable object, and it could be x's contents that change. E.g., if x refers to a dictionary,

x = root.winfo_dimensions()print x['width']

Then you could make it so that root keeps an instance of that dictionary itself, and updates it when the width changes. Maybe it only keeps one and returns that. But then you can also change the contents from elsewhere, and that's tricky.

I wouldn't do any of this at all and just call root.winfo_width() where needed. Explicit is better than implicit.


Depending on what you need exactly, @property decorator may do the trick (based on @BrenBarn's answer):

class X(object):    @property  # <-- this 'decorator' provides the necessary magic    def x(self):        return time.time()  # <-- just for example of refresh    def __repr__(self):        return str(self.x)

Now we can do:

>>> x = X()>>> x1386929249.63>>> x1386929250.27

But that may be a trick linked to the interpreter, but you still can do the following:

>>> x.x1386929251.14>>> x.x1386929253.01

If you have several such "dynamic properties", you can just group them in one class, and access them this way (but this may not be a good idea, in terms of readability, to hide dynamic behavior of a property).