Reputation: 3278
I have a class and a property writable_attributes
which is an array of attributes that should be available to bet set when the class is instantiated:
class User(object):
writable_attributes = ['username','email']
I want to be able to raise an error if another attribute is set if it's not in the list of writable_attributes
. I was browsing for a generic setter but I can't find anything to fit my needs. Something like:
user = User()
user.foo = 'bar' # This should raise an error since only `username` and `email` can be set
Upvotes: 2
Views: 171
Reputation: 251355
You may also be interested in __setattr__
. This overrides attribute setting on an object. slots has additional complications that setattr doesn't have.
Upvotes: 2
Reputation: 35059
First, reconsider if you really need to do this. It is usually over-engineering. If you do decide you really need to, take a look at __slots__
- if you rename your writable_attributes
to __slots__
, it will be an error to try to create more. If you need to avoid some existing ones being written to once they're set once, you can do that with properties.
Upvotes: 2
Reputation: 798546
It sounds like what you're really looking for is __slots__
.
Upvotes: 2