I want to create an immutable class that reads a file and do other things. I have problems with the mutability:
from dataclasses import dataclass
import io
@dataclass(frozen=True)
class Book:
filename: str
#file: io.TextIOWrapper
def __new__(cls, filename):
self = super().__new__(cls)
self.file = open(filename, "r")
return self
def __post_init__(self):
#self.file = open(self.filename, "r")
pass
def close(self):
self.file.close()
book = Book("testfile.txt")
book.close()
print(book)
This is the error I get:
Traceback (most recent call last):
File "D:\Sync1\Code\Python3\EconoPy\Version_0.2\test.py", line 32, in <module>
book = Book("testfile.txt")
File "D:\Sync1\Code\Python3\EconoPy\Version_0.2\test.py", line 17, in __new__
self.file = open(filename, "r")
File "<string>", line 4, in __setattr__
dataclasses.FrozenInstanceError: cannot assign to field 'file'
I want to set the attribute self.file from the input filename, but the 'frozening' is forbidding that. With the __post_init__ I can do that if I remove the 'frozening'.