Class Variable Question

Bob Kline bkline at rksystems.com
Mon Apr 9 13:48:55 EDT 2001


On Mon, 9 Apr 2001, Alex Martelli wrote:

> "Robert Johnson" <rjohnson at exotic-eo.com> wrote in message
> news:3ad1c7e9$0$196$e2e8da3 at nntp.cts.com...
> 
> > Is there a way to prevent this so users cannot add variables?
> 
> Nope (how would one distinguish 'users' from other pieces
> of code for this purpose?).  You can wrap objects up into
> a Bastion if you have security worries.
> 
> > It seems to me that the user could just override a class with
> > unrelated data.
> 
> Sure, just like he could say x=y-z when actually meaning x=y+z, and
> a zillion other horrible programming errors.
> 
> Hopefully the user will then run some _tests_ (what other ways would
> you suggest for the "plus oops I meant minus" kind or errors to be
> caught...?), fix the mistakes he then finds as a result of his
> testing, and have code with fewer errors -- including code free from
> accidental, erroneous rebindings of all kinds.

Ah, you have to love these "You-mean-you-actually-put-bugs-in-your-
software-that-you-have-difficulty-finding?" responses, especially when
the alternating refrain from Python fans is "Why on earth would you want
to use a language which doesn't eliminate memory management bugs for
you?"

And now for something completely different.  Here's a (possibly) more
helpful response.  You might want to try something along these lines:

$ cat SafeClass.py
class SafeClass:
    members = ('foo','bar')
    def __init__(self):
        self.foo = 42
        self.bar = 'floccinaucinihilipilification'
    def __setattr__(self, name, value):
        if name not in SafeClass.members:
            raise "%s is not a member of SafeClass" % name
        self.__dict__[name] = value
$ python
Python 1.5.2 (#1, Aug 25 2000, 09:33:37)  [GCC 2.96 20000731 (experimental)] on linux-i386
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> from SafeClass import SafeClass
>>> sc = SafeClass()
>>> sc.foo = 43
>>> sc.fud = 44
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "SafeClass.py", line 5, in __setattr__
    raise ("%s is not a member of SafeClass" % (name,))
fud is not a member of SafeClass

As you can see, this approach needs another five lines in the class
definition, and of course the members list would have to be maintained,
but the example demonstrates that the correct answer to your question
("Is there a way to prevent this so users cannot add variables?") is
actually "Yes."  The approach doesn't prevent intentional undermining of
the safety measure, but it will catch the sorts of mistakes you're
asking about.

Hope this helps.

-- 
Bob Kline
mailto:bkline at rksystems.com
http://www.rksystems.com






More information about the Python-list mailing list