Overloading assignment operator

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Tue Jan 23 17:17:26 EST 2007


On Tue, 23 Jan 2007 19:42:01 +0100, Peter Otten wrote:

> Achim Domma wrote:
> 
>> I want to use Python to script some formulas in my application. The user
>> should be able to write something like
>> 
>> A = B * C
>> 
>> where A,B,C are instances of some wrapper classes. Overloading * is no
>> problem but I cannot overload the assignment of A. I understand that
>> this is due to the nature of Python, but is there a trick to work around
>> this?
> 
>>>> class D(dict):
> ...     def __setitem__(self, key, value):
> ...             print key, "<--", value
> ...             dict.__setitem__(self, key, value)
> ...
>>>> namespace = D(B=42, C=24)
>>>> exec "A = B * C" in namespace
> A <-- 1008

Very clever, except:

(1) The Original Poster's requirement was for a "clean syntax" and 
'exec "A = B * C" in namespace' is anything but a clean syntax.

(2) The O.P. specifies that the syntax is for use by his users. We don't
know who these users are, but can you see users getting this right and not
ignoring the namespace argument?

(3) Even if they do use the namespace argument, how hard is it for the
users to break the security of your exec?

>>> exec "A = B * C;import os;os.system('ls -l break-something')" in namespace
A <-- 1008
os <-- <module 'os' from '/usr/lib/python2.4/os.pyc'>
-rw-rw-r-- 1 steve steve 0 Jan 24 08:27 break-something

Using exec on user-supplied data is just begging to be p0wned.


-- 
Steven.




More information about the Python-list mailing list