2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02:00
A class without an explicit extension of object (``++class ClassName(object)++``) is considered an old-style class, and ``++__slots__++`` declarations are ignored in old-style classes. Having such a declaration in an old-style class could be confusing for maintainers and lead them to make false assumptions about the class.
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,python]
2021-04-28 16:49:39 +02:00
----
class A:
__slots__ = ["id"] # Noncompliant; this is ignored
def __init__(self):
self.id = id
self.name = "name" # name wasn't declared in __slots__ but there's no error
a = A()
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,python]
2021-04-28 16:49:39 +02:00
----
class A(object): # Converting to a new-style class is the preferred method of addressing this issue
__slots__ = ["id"]
def __init__(self):
self.id = id
self.name = "name" # "name" is not listed in __slots__, so as expected there is an error in this line
a = A()
----
or
2022-02-04 17:28:24 +01:00
[source,python]
2021-04-28 16:49:39 +02:00
----
class A:
def __init__(self):
self.id = id
self.name = "name"
a = A()
----
2021-04-28 18:08:03 +02:00
2021-09-20 15:38:42 +02:00
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
endif::env-github,rspecator-view[]