84

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?

Eric
  • 87,154
  • 48
  • 211
  • 332
Caruccio
  • 2,679
  • 3
  • 16
  • 12
  • 1
    Use case: people are going to write small scripts using my service API, and I want to prevent them from changing internal data and propagate this change to the next script. – Caruccio Jun 13 '12 at 23:39
  • 5
    Python explicitly avoids promising that a malicious or ignorant coder will be prevented from access. Other languages allow you to avoid some programmer error due to ignorance, but people have an uncanny ability to code around them. – msw Jun 13 '12 at 23:43
  • you could execute that code using `exec in d` where d is some dictionary. if the code is on module level, every assignment should get sent back to the dictionary. You could either restore your values after execution/check whether values changed, or intercept the dictionary assignment, i.e. replace the dictionary of variables with another object. – Ant6n Mar 02 '14 at 01:57
  • Oh no, so it's impossible to simulate VBA behaviour like `ScreenUpdating = False` on module level – Winand Sep 01 '15 at 06:13
  • You can use the [`__all__` attribute of your module](https://docs.python.org/3/tutorial/modules.html#importing-from-a-package) to make it harder for people to export private data. This is a common approach for the Python Standard Library – Ben Jan 13 '17 at 22:42
  • Can we generalize this for global assignment operation? Like `x=1` and `x=2` will give error. – Poojan Nov 13 '19 at 16:46

11 Answers11

78

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.

steveha
  • 67,444
  • 18
  • 86
  • 112
  • 4
    Using `@property` with a getter but no setter is a similar way to pseudo-overload assignment. – jtpereyda Dec 16 '15 at 20:26
  • 2
    `getattr(self, "_locked", None)` instead of `self.__dict__.get("_locked")`. – Vedran Šego Apr 09 '18 at 13:50
  • @VedranŠego I followed your suggestion but used `False` instead of `None`. Now if someone deletes the `_locked` member variable, the `.get()` call won't raise an exception. – steveha May 30 '18 at 06:09
  • 1
    @steveha Did it actually raise an exception for you? `get` defaults to `None`, unlike `getattr` which would indeed raise an exception. – Vedran Šego May 30 '18 at 09:08
  • Ah, no, I didn't see it raise an exception. Somehow I overlooked that you were suggesting to use `getattr()` rather than `.__dict__.get()`. I guess it's better to use `getattr()`, that's what it's for. – steveha Jun 07 '18 at 04:44
31

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

msw
  • 40,500
  • 8
  • 77
  • 106
8

I don't think it's possible. The way I see it, assignment to a variable doesn't do anything to the object it previously referred to: it's just that the variable "points" to a different object now.

In [3]: class My():
   ...:     def __init__(self, id):
   ...:         self.id=id
   ...: 

In [4]: a = My(1)

In [5]: b = a

In [6]: a = 1

In [7]: b
Out[7]: <__main__.My instance at 0xb689d14c>

In [8]: b.id
Out[8]: 1 # the object is unchanged!

However, you can mimic the desired behavior by creating a wrapper object with __setitem__() or __setattr__() methods that raise an exception, and keep the "unchangeable" stuff inside.

Lev Levitsky
  • 55,704
  • 18
  • 130
  • 156
7

Inside a module, this is absolutely possible, via a bit of dark magic.

import sys
tst = sys.modules['tst']

class Protect():
  def __assign__(self, value):
    raise Exception("This is an ex-parrot")

var = Protect()  # once assigned...

Module = type(tst)
class ProtectedModule(Module):
  def __setattr__(self, attr, val):
    exists = getattr(self, attr, None)
    if exists is not None and hasattr(exists, '__assign__'):
      exists.__assign__(val)
    super().__setattr__(attr, val)

tst.__class__ = ProtectedModule

Note that even from within the module, you cannot write to the protected variable once the class change happens. The above example assumes the code resides in a module named tst. You can do this in the repl by changing tst to __main__.

Perkins
  • 2,031
  • 19
  • 20
4

Using the top-level namespace, this is impossible. When you run

var = 1

It stores the key var and the value 1 in the global dictionary. It is roughly equivalent to calling globals().__setitem__('var', 1). The problem is that you cannot replace the global dictionary in a running script (you probably can by messing with the stack, but that is not a good idea). However you can execute code in a secondary namespace, and provide a custom dictionary for its globals.

class myglobals(dict):
    def __setitem__(self, key, value):
        if key=='val':
            raise TypeError()
        dict.__setitem__(self, key, value)

myg = myglobals()
dict.__setitem__(myg, 'val', 'protected')

import code
code.InteractiveConsole(locals=myg).interact()

That will fire up a REPL which almost operates normally, but refuses any attempts to set the variable val. You could also use execfile(filename, myg). Note this doesn't protect against malicious code.

Mad Physicist
  • 76,709
  • 19
  • 122
  • 186
Perkins
  • 2,031
  • 19
  • 20
  • This is dark magic! I fully expected to just find a bunch of answers where people suggest using an object explicitly with an overridden setattr, didn't think about overriding globals and locals with a custom object, wow. This must make PyPy cry though. – Joseph Garvin Jul 20 '17 at 06:19
3

No there isn't

Think about it, in your example you are rebinding the name var to a new value. You aren't actually touching the instance of Protect.

If the name you wish to rebind is in fact a property of some other entity i.e myobj.var then you can prevent assigning a value to the property/attribute of the entity. But I assume thats not what you want from your example.

Tim Hoffman
  • 12,908
  • 1
  • 15
  • 28
  • 1
    Almost there! I tried to overload the module's `__dict__.__setattr__` but `module.__dict__` itself is read-only. Also, type(mymodule) == , and it's not instanceable. – Caruccio Jun 14 '12 at 11:53
3

Yes, It's possible, you can handle __assign__ via modify ast.

pip install assign

Test with:

class T():
    def __assign__(self, v):
        print('called with %s' % v)
b = T()
c = b

You will get

>>> import magic
>>> import test
called with c

The project is at https://github.com/RyanKung/assign And the simpler gist: https://gist.github.com/RyanKung/4830d6c8474e6bcefa4edd13f122b4df

Ryan Kung
  • 235
  • 1
  • 5
  • There's something I don't get... Shouldn't it be `print('called with %s' % self)`? – zezollo Nov 09 '17 at 16:34
  • 1
    There are a few things I don't understand: 1) How (and why?) does the string `'c'` end up in the `v` argument for the `__assign__` method? What does your example actually show? It confuses me. 2) When would this be useful? 3) How does this relate to the question? For it to correspond the the code written in the question, wouldn't you need to write `b = c`, not `c = b`? – HelloGoodbye Nov 12 '19 at 09:38
2

In the global namespace this is not possible, but you could take advantage of more advanced Python metaprogramming to prevent multiple instances of a the Protect object from being created. The Singleton pattern is good example of this.

In the case of a Singleton you would ensure that once instantiated, even if the original variable referencing the instance is reassigned, that the object would persist. Any subsequent instances would just return a reference to the same object.

Despite this pattern, you would never be able to prevent a global variable name itself from being reassigned.

Community
  • 1
  • 1
jathanism
  • 30,623
  • 9
  • 64
  • 86
  • A singleton is not enough, since `var = 1` does not calls the singleton mechanism. – Caruccio Jun 14 '12 at 11:54
  • Understood. I apologize if I wasn't clear. A singleton would prevent further instances of an object (e.g. `Protect()`) from being created. There is no way to protect the originally assigned name (e.g. `var`). – jathanism Jun 14 '12 at 18:11
  • @Caruccio. Unrelated, but 99% of the time, at least in CPython, 1 behaves as a singleton. – Mad Physicist Sep 18 '18 at 15:13
2

A ugly solution is to reassign on destructor. But it's no real overload assignment.

import copy
global a

class MyClass():
    def __init__(self):
            a = 1000
            # ...

    def __del__(self):
            a = copy.copy(self)


a = MyClass()
a = 1
Nuno André
  • 2,869
  • 1
  • 21
  • 31
ecn
  • 21
  • 1
2

Generally, the best approach I found is overriding __ilshift__ as a setter and __rlshift__ as a getter, being duplicated by the property decorator. It is almost the last operator being resolved just (| & ^) and logical are lower. It is rarely used (__lrshift__ is less, but it can be taken to account).

Within using of PyPi assign package only forward assignment can be controlled, so actual 'strength' of the operator is lower. PyPi assign package example:

class Test:

    def __init__(self, val, name):
        self._val = val
        self._name = name
        self.named = False

    def __assign__(self, other):
        if hasattr(other, 'val'):
            other = other.val
        self.set(other)
        return self

    def __rassign__(self, other):
        return self.get()

    def set(self, val):
        self._val = val

    def get(self):
        if self.named:
            return self._name
        return self._val

    @property
    def val(self):
        return self._val

x = Test(1, 'x')
y = Test(2, 'y')

print('x.val =', x.val)
print('y.val =', y.val)

x = y
print('x.val =', x.val)
z: int = None
z = x
print('z =', z)
x = 3
y = x
print('y.val =', y.val)
y.val = 4

output:

x.val = 1
y.val = 2
x.val = 2
z = <__main__.Test object at 0x0000029209DFD978>
Traceback (most recent call last):
  File "E:\packages\pyksp\pyksp\compiler2\simple_test2.py", line 44, in <module>
    print('y.val =', y.val)
AttributeError: 'int' object has no attribute 'val'

The same with shift:

class Test:

    def __init__(self, val, name):
        self._val = val
        self._name = name
        self.named = False

    def __ilshift__(self, other):
        if hasattr(other, 'val'):
            other = other.val
        self.set(other)
        return self

    def __rlshift__(self, other):
        return self.get()

    def set(self, val):
        self._val = val

    def get(self):
        if self.named:
            return self._name
        return self._val

    @property
    def val(self):
        return self._val


x = Test(1, 'x')
y = Test(2, 'y')

print('x.val =', x.val)
print('y.val =', y.val)

x <<= y
print('x.val =', x.val)
z: int = None
z <<= x
print('z =', z)
x <<= 3
y <<= x
print('y.val =', y.val)
y.val = 4

output:

x.val = 1
y.val = 2
x.val = 2
z = 2
y.val = 3
Traceback (most recent call last):
  File "E:\packages\pyksp\pyksp\compiler2\simple_test.py", line 45, in <module>
    y.val = 4
AttributeError: can't set attribute

So <<= operator within getting value at a property is the much more visually clean solution and it is not attempting user to make some reflective mistakes like:

var1.val = 1
var2.val = 2

# if we have to check type of input
var1.val = var2

# but it could be accendently typed worse,
# skipping the type-check:
var1.val = var2.val

# or much more worse:
somevar = var1 + var2
var1 += var2
# sic!
var1 = var2
1

As mentioned by other people, there is no way to do it directly. It can be overridden for class members though, which is good for many cases.

As Ryan Kung mentioned, the AST of a package can be instrumented so that all assignments can have a side effect if the class assigned implements specific method(s). Building on his work to handle object creation and attribute assignment cases, the modified code and a full description is available here:

https://github.com/patgolez10/assignhooks

The package can be installed as: pip3 install assignhooks

Example <testmod.py>:

class SampleClass():

   name = None

   def __assignpre__(self, lhs_name, rhs_name, rhs):
       print('PRE: assigning %s = %s' % (lhs_name, rhs_name))
       # modify rhs if needed before assignment
       if rhs.name is None:
           rhs.name = lhs_name
       return rhs

   def __assignpost__(self, lhs_name, rhs_name):
       print('POST: lhs', self)
       print('POST: assigning %s = %s' % (lhs_name, rhs_name))


def myfunc(): 
    b = SampleClass()
    c = b
    print('b.name', b.name)

to instrument it, e.g. <test.py>

import assignhooks

assignhooks.instrument.start()  # instrument from now on

import testmod

assignhooks.instrument.stop()   # stop instrumenting

# ... other imports and code bellow ...

testmod.myfunc()

Will produce:

$ python3 ./test.py

POST: lhs <testmod.SampleClass object at 0x1041dcc70>
POST: assigning b = SampleClass
PRE: assigning c = b
POST: lhs <testmod.SampleClass object at 0x1041dcc70>
POST: assigning c = b
b.name b
patgolez10
  • 11
  • 1