jcomeau_ictx
jcomeau_ictx

Reputation: 38432

pythonic way of modifying a mutable inside an immutable

let's say I have a class that behaves as an int to the outside world, but in fact is a mutable object that has a fixed place within several structures. if n is my object, I can update it now by writing n.update(34), but I find I'm always wanting to write n = 34 instead. I've glanced over http://docs.python.org/reference/datamodel.html, and don't see anything like an __assign__ or __value__ attribute that would let me trap the = operator and allow me to update my object rather than assign an int to the variable n, throwing my object away. better still, when a mutable is inside a tuple t = (m, n), I would like to update my mutable with t[1] = 34, but Python sees that as attempting to modify an immutable.

so I guess the answer would be, based upon what little of that document I was able to grok, that what I'm attempting is not Pythonic. so if I can't do it the way I want, what would be the next best thing? such that if someone has to maintain my code someday, it won't be overly offensive.

Upvotes: 1

Views: 134

Answers (1)

kindall
kindall

Reputation: 184191

Your basic obj.value = newvalue is basically the best, most understandable way. As you surmise, it is not possible to override assignment in Python.

You could implement __call__() on your class to do the assignment, so that you can just do obj(newvalue). However, it's not at all clear to the casual reader that that's a reassignment.

Another idea would be to implement __ilshift__() so you can do obj <<= newval. That at least looks like some kind of mutant reassignment operation if you squint hard enough. If it weren't a numeric type, I might consider it. But << has a well-defined meaning with int and, since you're masquerading as that type, it would IMHO be confusing to use it in this way.

Upvotes: 3

Related Questions