On Tue, 27 Feb 2007 06:40:29 +0000, Alan Isaac wrote:

> "Ben Finney" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>> The Pythonic design is: don't expect to have such control over users
>> of your code.
> 
> I know this is a popular response,

It's popular for good reason.


> but the fact of the matter remains that
> it can be helpful to know when someone
> tries to set a value for a nonexisting attribute.

I'm afraid your understanding of the word "fact" is different from my
understanding of the word "fact".

But be that as it may, if you wish to waste^H^H^H^H^H spend time
trying to prevent people from adding attributes to their instances,
Just Because, you can do something like this:

class Difficult(object):
    def __setattr__(self, name, value):
        if self.__dict__.has_key(name):
            print "'%s' exists as an instance attribute" % name
            self.__dict__[name] = value
        elif self.__class__.__dict__.has_key(name):
            print "'%s' exists as a class attribute" % name
            self.__class__.__dict__[name] = value
        else:
            print "Can't create new attributes, 'cos I said so!"


There ought to be a name for that anti-pattern of molly-coddling,
bondage-and-domination philosophy of "you're only allowed to use my class
the way I want you to use it".

(Excuse my cynicism, for all I know you've got a really good reason for
wanting to do this, perhaps as part of a cold-fusion machine.)



-- 
Steven D'Aprano 

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to