What is a mechanism equivalent to "trace variable w ..." in Tcl for Python?

Random832 random832 at fastmail.com
Fri Sep 30 15:45:07 EDT 2016


On Fri, Sep 30, 2016, at 14:42, Ned Batchelder wrote:
> On Friday, September 30, 2016 at 2:16:10 PM UTC-4, Les Cargill wrote:
> > What is an equivalent mechanism in Python?
> 
> There's no way* to hook into "x = 2", but you could hook into "x.a = 2"
> if you wanted do, by defining __setattr__ on x's class.

That or set cls.a to be a descriptor (using either @property or a
custom-made descriptor class)

class motor:
    @property
    def RPM(self): return self._RPM
    @RPM.setter
    def RPM(self, value):
        print("RPM changed from", self._RPM, "to", value)
        self._RPM = value

If you really wanted to get crazy, you could use self.__dict__['RPM']
instead of self._RPM, which would allow you to inject the descriptor
separately after the class has already been defined and used. Making it
work right if the definition of motor already has an RPM descriptor [for
example, if it uses __slots__] is an exercise for the reader.

> *OK, there might be some crazy hack involving your own class as the
> globals for a module or something, but it sounds ill-advised.

You can make your own class to be *the module itself* to support
external code's "mod.x = 2", but AIUI that won't apply to plain
assignment, which bypasses most of the relevant machinery.



More information about the Python-list mailing list