can't add variables to instances of built-in classes

Steven D'Aprano steve at pearwood.info
Sun Jul 17 11:04:01 EDT 2016


On Sun, 17 Jul 2016 09:50 pm, Wilson Ong wrote:

> 
>> Use this feature sparingly, only when you know that there are going to be
>> many (millions rather than thousands) of Test instances.
> 
> Why use it sparingly? Is it for extensibility? What if I'm pretty sure
> that my class is going to have exactly these attributes only?

It's your own code, you can do anything you like, its not like the Python
Police will come and arrest you.

But *best practice* is for instances to have a __dict__, which allows them
to have instance attributes. Python code expects to be able to inspect, and
write to, the instance __dict__, and if you don't have one, you may break
code that doesn't expect it.

But it is not a hard rule, just a strong recommendation. There are
exceptions. Most built-ins don't have __dict__, partly as an optimization,
and partly to allow sharing of builtins across sub-interpreters;

__slots__ was specifically invented so that classes created in Python could
avoid creating a per-instance __dict__, for cases where you expect to have
vast numbers of instances with only a fixed number of attributes. In this
case, having an unused __dict__ can be wasteful.

But note that in recent versions of Python, there is less need to use
__slots__, and a much smaller benefit. The reason is that the instance
dicts can now share storage for their keys.

https://www.python.org/dev/peps/pep-0412/

__slots__ is not obsolete, but 99% of the time you shouldn't bother with it.



-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list