1

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the ideas, and for improving on my limited understanding of these concepts. I'll leave the code alone for now, as I have real work to do with it still, but when it comes time for an update I'll make a decision.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.