__init__, __slot__ and **keywordargs

Peter Otten __peter__ at web.de
Fri Jan 9 11:42:39 EST 2004


Zunbeltz Izaola wrote:

> Peter Otten <__peter__ at web.de> writes:
> 
>> 
>> You misspelt: in fact it's __slots__, and it will work as expected. As
>> far
> 
> Hurg!!! :-( This kine of mistakes will become me crazy.
> 
>> as I know slots are an optimization technique that is useful to save some
>> space, when you have many (that would be millions) of small objects. It's
>> not meant as a safety belt for the programmer.
> 
> But, I think it can be considered "a safety belt for the programmer" ,
> When you do

It can, but I think it's contrary to the Python style, which relies heavily
on unit tests. If you to want ensure a limited set of attributes, then why
would you allow both an integer and a Date for the Birthday - if you follow
this road, you end up programming in Java, because it's designed for that
kind of safety. Most Pythonistas think that you are spending too much time
on errors that comprise only a small fraction of what goes wrong in real
programs.

> instance.attribute
> 
> you get and AttributeError if attribute is not in the __slots__
> (It would help to avoid misspells, like i've done!!)

Note that you already get an AttributeError for read access. Write access
aka rebinding is used only in a fraction of all accesses and prohibiting it
for arbitrary attribute names IMHO significantly impairs the usefulness of
Python's object model.

>> In your case, I wouldn't use it, but rather not initialize the attributes
>> not given as constructor - __init__() - arguments. Also, I would consider
>> the ability to provide additional arguments, say "Nickname", not a
>> bug but
> 
> What do you mean with additional arguments? (My code was not the full
> code)

Let's assume you have mandatory arguments Firstname and Surname but want to
allow for other information. A constructor reflecting that would then be

def __init__(self, Firstname, Surname, **OptionalAttributes)

It's up to the clientcode to decide what these optional attributes may be,
so they could vary in different contexts. This in turn makes your class
useful for a broader range of usecases.

Peter




More information about the Python-list mailing list