Calling generated `__init__` in custom `__init__` override on dataclass

2024/11/14 15:14:32

Currently I have something like this:

@dataclass(frozen=True)
class MyClass:a: strb: strc: strd: Dict[str, str]

...which is all well and good except dicts are mutable, so I can't use my class to key another dictionary.

Instead, I'd like field d to be something like a FrozenSet[Tuple[str, str]], but I'd still like someone constructing an instance of my class to be able to pass a dictionary on the constructor as this is much more intuitive.

So I'd like to do something like

@dataclass(frozen=True)
class MyClass:a: strb: strc: strd: FrozenSet[Tuple[str, str]] = field(init=False)def __init__(self, a, b, c, d: Dict[str, str]):self.original_generated_init(a, b, c)  # ???object.setattr(self, 'd', frozenset(d.items()))  # required because my dataclass is frozen

How do I achieve this? Alternatively is there a more elegant way to achieve the same thing?

Answer

You can use an InitVar and assign to d in __post_init__:

@dataclass(frozen=True)
class MyClass:a: strb: strc: strd: FrozenSet[Tuple[str, str]] = field(init=False)d_init: InitVar[Dict[str, str]]def __post_init__(self, d_init):object.__setattr__(self, 'd', frozenset(d_init.items()))
https://en.xdnf.cn/q/72050.html

Related Q&A

Python Watchdog process existing files on startup

I have a simple Watchdog and Queue process to monitor files in a directory. Code taken from https://camcairns.github.io/python/2017/09/06/python_watchdog_jobs_queue.htmlimport time from watchdog.events…

Updating Text In Entry (Tkinter)

The piece of code below takes input from user through a form and then returns the input as multiplied by 2. What I want to do is, when a user types a number (for example 5) and presses the "Enter&…

Python prevent overflow errors while handling large floating point numbers and integers

I am working on a python program to calculate numbers in the Fibonacci sequence. Here is my code:import math def F(n):return ((1+math.sqrt(5))**n-(1-math.sqrt(5))**n)/(2**n*math.sqrt(5)) def fib(n):for…

Python selenium sending keys into textarea

Im using Python 3.4.4 to access a website (https://readability-score.com/) that has a textarea, which dynamically updates when new values are added. Im trying to input a string into that textarea box b…

how to run several executable using python?

I have an executable under linux. I have an 8 core processor. I want to run 8 different instances of the same executable with different arguments.I tried os.system("process_name args")It does…

How to retrieve only arabic texts from a string using regular expression?

I have a string which has both Arabic and English sentences. What I want is to extract Arabic Sentences only.my_string=""" What is the reason ذَلِكَ الْكِتَابُ لَا رَ…

Formatted output in OpenOffice/Microsoft Word with Python

I am working on a project (in Python) that needs formatted, editable output. Since the end-user isnt going to be technically proficient, the output needs to be in a word processor editable format. The …

Issue in calling Python code from Java (without using jython)

I found this as one of the ways to run (using exec() method) python script from java. I have one simple print statement in python file. However, my program is doing nothing when I run it. It neither pr…

AttributeError: tuple object has no attribute dim, when feeding input to Pytorch LSTM network

I am trying to run the following code:import matplotlib.pylab as plt import numpy as np import torch import torch.nn as nnclass LSTM(nn.Module):def __init__(self, input_shape, n_actions):super(LSTM, se…

Python - Idiom to check if string is empty, print default

Im just wondering, is there a Python idiom to check if a string is empty, and then print a default if its is?(The context is Django, for the __unicode__(self) function for UserProfile - basically, I w…