design question: no new attributes

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Tue Feb 27 02:24:59 EST 2007


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

> "Ben Finney" <bignose+hates-spam at benfinney.id.au> wrote in message
> news:mailman.4438.1172534289.32031.python-list at python.org...
>> 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 




More information about the Python-list mailing list