[New-bugs-announce] [issue46550] __slots__ updates despite being read-only
Ian Lee
report at bugs.python.org
Thu Jan 27 09:55:32 EST 2022
New submission from Ian Lee <ianlee1521 at gmail.com>:
Hi there - I admit that I don't really understand the internals here, so maybe there is a good reason for this, but I thought it was weird when I just ran across it.
If I create a new class `A`, and set it's `__slots`:
```python
➜ ~ docker run -it python:3.10
Python 3.10.2 (main, Jan 26 2022, 20:07:09) [GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class A(object):
... __slots__ = ["foo"]
...
>>> A.__slots__
['foo']
```
If I then go to add a new attribute to extend it on the class, that works:
```python
>>> A.__slots__ += ["bar"]
>>> A.__slots__
['foo', 'bar']
```
But then if I create an instance of that class, and try to update `__slots__` on that instnace, I get an AttributeError that `__slots__` is read-only, and yet it still is updating the `__slots__` variable:
```python
>>> a = A()
>>> a.__slots__
['foo', 'bar']
>>> a.__slots__ += ["baz"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object attribute '__slots__' is read-only
>>> a.__slots__
['foo', 'bar', 'baz']
>>> A.__slots__
['foo', 'bar', 'baz']
```
Maybe there is a good reason for this, but I was definitely surprised that I would get a "this attribute is read-only" error, and yet still see that attribute updated.
I first found this in python 3.8.5, but I also tested using docker to generate the above example using docker python:3.10 which gave me python 3.10.2.
Cheers!
----------
components: Library (Lib)
messages: 411886
nosy: IanLee1521
priority: normal
severity: normal
status: open
title: __slots__ updates despite being read-only
type: behavior
versions: Python 3.10, Python 3.8
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue46550>
_______________________________________
More information about the New-bugs-announce
mailing list