Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to overload Python assignment?

Is there a magic method that can overload the assignment operator, like __assign__(self, new_value)?

I'd like to forbid a re-bind for an instance:

class Protect():   def __assign__(self, value):     raise Exception("This is an ex-parrot")  var = Protect()  # once assigned... var = 1          # this should raise Exception() 

Is it possible? Is it insane? Should I be on medicine?

like image 991
Caruccio Avatar asked Jun 13 '12 23:06

Caruccio


People also ask

Can assignment operator be overloaded?

You can overload the assignment operator (=) just as you can other operators and it can be used to create an object just like the copy constructor. Following example explains how an assignment operator can be overloaded.

How do you overload in Python?

In Python, overloading is achieved by overriding the method which is specifically for that operator, in the user-defined class. For example, __add__(self, x) is a method reserved for overloading + operator, and __eq__(self, x) is for overloading == .

Does Python has an assignment operator?

Assignment operators are used in Python to assign values to variables. a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left.

What is operator overloading in Python with example?

Operator overloading in Python is the ability of a single operator to perform more than one operation based on the class (type) of operands. For example, the + operator can be used to add two numbers, concatenate two strings or merge two lists.


2 Answers

The way you describe it is absolutely not possible. Assignment to a name is a fundamental feature of Python and no hooks have been provided to change its behavior.

However, assignment to a member in a class instance can be controlled as you want, by overriding .__setattr__().

class MyClass(object):     def __init__(self, x):         self.x = x         self._locked = True     def __setattr__(self, name, value):         if self.__dict__.get("_locked", False) and name == "x":             raise AttributeError("MyClass does not allow assignment to .x member")         self.__dict__[name] = value  >>> m = MyClass(3) >>> m.x 3 >>> m.x = 4 Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File "<stdin>", line 7, in __setattr__ AttributeError: MyClass does not allow assignment to .x member 

Note that there is a member variable, _locked, that controls whether the assignment is permitted. You can unlock it to update the value.

like image 163
steveha Avatar answered Sep 19 '22 06:09

steveha


No, as assignment is a language intrinsic which doesn't have a modification hook.

like image 39
msw Avatar answered Sep 23 '22 06:09

msw