self.__dict__ tricks

Tim Johnson tim at
Sat Oct 31 17:15:48 CET 2009

On 2009-10-31, Steven D'Aprano <steve at> wrote:
>>> Idiomatic Python is to use CamelCase for classes.
>>   Can you point me to a discussion on Idiomatic Python, CamelCase and
>>   other matters?
<...> See PEP 8:
  Got it. Thanks.
>>> invalid parameter shouldn't raise the same error as failing an
>>> attribute look-up. That's misleading and confusing.
>> What error class or other approach do you recommend?
> Unless you have a good reason for doing something different, do what 
> Python built-ins do:
>>>> int('123', parrot=16)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: 'parrot' is an invalid keyword argument for this function
 Understood. I kyped that method from from an open source library module
 and have been using it ever since.
>>> I also should point out that your trick will fail if you are using
>>> __slots__.
>>   ??. Will research that. Elaborate if you wish.
> __slots__ are an optimization for making objects smaller than normal if 
> you have many millions of them:
>>   If the class grows - and I expect it will - I'd prefer to stick with
>>   the keywords approach. That approach also allows me to use a
>>   dictionary to initialize the object.
> You can still do that with named parameters.
>>>> class Parrot:
> ...     def __init__(self, name='Polly', colour='blue',

>>>> p = Parrot("Sparky", 'white', "Cockatoo")
>>>> data = dict(colour='red', name='Fred', foo=1)
>>>> p = Parrot(**data)  # raise an error with bad input
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: __init__() got an unexpected keyword argument 'foo'
<...> OK. That makes sense. You have made a believer of me.

I really appreciate all the time you have taken with this.
Many programmers I know stay away from 'lists' such as this, because
they are afraid to show their ignorance. Me, I'm fearless, and I have
learned a lot that I might not have otherwise.

take care
tim at

More information about the Python-list mailing list