Is there a way to use a dataclass, with fields with defaults, with __slots__

2024/9/20 11:47:46

I would like to put __slots__ on a dataclass with fields with defaults. When I try do that, I get this error:

>>> @dataclass
... class C:
...     __slots__ = ('x', 'y', )
...     x: int
...     y: int = 1
...     
Traceback (most recent call last):File "<input>", line 1, in <module>
ValueError: 'y' in __slots__ conflicts with class variable

Is there a way to achieve this?

Answer

There is, by using the @add_slots decorator by ericvsmith:

import dataclassesdef add_slots(cls):# Need to create a new class, since we can't set __slots__#  after a class has been created.# Make sure __slots__ isn't already set.if '__slots__' in cls.__dict__:raise TypeError(f'{cls.__name__} already specifies __slots__')# Create a new dict for our new class.cls_dict = dict(cls.__dict__)field_names = tuple(f.name for f in dataclasses.fields(cls))cls_dict['__slots__'] = field_namesfor field_name in field_names:# Remove our attributes, if present. They'll still be#  available in _MARKER.cls_dict.pop(field_name, None)# Remove __dict__ itself.cls_dict.pop('__dict__', None)# And finally create the class.qualname = getattr(cls, '__qualname__', None)cls = type(cls)(cls.__name__, cls.__bases__, cls_dict)if qualname is not None:cls.__qualname__ = qualnamereturn cls

Usage:

>>> @add_slots
... @dataclass
... class C:
...     __slots__ = ('x', 'y', )
...     x: int
...     y: int = 1

Adding __slots__ manually works as long as there are no defaults. You can find related the Github issue here

https://en.xdnf.cn/q/72350.html

Related Q&A

Read remote file using python subprocess and ssh?

How can I read data from a big remote file using subprocess and ssh?

Django - get_queryset() missing 1 required positional argument: request

I was trying to make an API using REST Framework for uploading a file to the server and my codes are below.If you have any other easy method to do the same please post your code.models.pyfrom django.db…

Storing elements of one list, in another list - by reference - in Python?

I just thought Id jot this down now that Ive seen it - it would be nice to get a confirmation on this behavior; I did see How do I pass a variable by reference?, but Im not sure how to interpret it in…

Joining Two Different Dataframes on Timestamp

Say I have two dataframes:df1: df2: +-------------------+----+ +-------------------+-----+ | Timestamp |data| | Timestamp |stuff| +-------------------+---…

Find if the array contain a 2 next to a 2

I am stuck on this problemGiven an array of ints, return True if the array contains a 2 next to a 2 somewhere.has22([1, 2, 2]) → True has22([1, 2, 1, 2]) → False has22([2, 1, 2]) → FalseI know the b…

AttributeError: xml.etree.ElementTree.Element object has no attribute encode

Im trying to make a desktop notifier, and for that Im scraping news from a site. When I run the program, I get the following error.news[child.tag] = child.encode(utf8) AttributeError: xml.etree.Element…

How to parse code (in Python)?

I need to parse some special data structures. They are in some somewhat-like-C format that looks roughly like this:Group("GroupName") {/* C-Style comment */Group("AnotherGroupName")…

Using OpenCV detectMultiScale to find my face

Im pretty sure I have the general theme correct, but Im not finding any faces. My code reads from c=cv2.VideoCapture(0), i.e. the computers videocamera. I then have the following set up to yield where …

Get marginal effects for sklearn logistic regression

I want to get the marginal effects of a logistic regression from a sklearn modelI know you can get these for a statsmodel logistic regression using .get_margeff(). Is there nothing for sklearn? I want…

How to use win32com.client.constants with MS Word?

Whats wrong with this code? Why win32com.client.constants doesnt have attribute wdWindowStateMinimize?>>> import win32com.client >>> w=win32com.client.Dispatch("Word.Applicatio…