Overloading assignment operator
__peter__ at web.de
Wed Jan 24 00:07:35 CET 2007
Steven D'Aprano wrote:
> 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
>>>>> 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?
I thought he might hide everything but the expression
A = B * C
from the user.
> (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
> 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.
Yes. Unless the application is deployed to the user's machine, in which case
he has more straightforward methods to destroy his own data.
More information about the Python-list