Python Forum
append str to list in dataclass
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
append str to list in dataclass
#1
Dear community,

I'm trying to append str to a list, which is in a dataclass.
I'm totally new to dataclasses.
I used to use a textfile for storing strings.

Then I read about dataclasses for storing data.

What is the simplest way for appending string to a list in a dataclass?

When I try mylist: list = []
then it is said to use default_factory...

@dataclass
class C():
    mylist: list
    a: str

    def __post_init__(self):
        return self.mylist.append(self.a)


c = C("a")
print(c.mylist)
c = C("b")
print(c.mylist)
mylist should be ["a", "b"].

Thanks a lot for the help, I did a lot of googling, but with no success...
Reply
#2
No, it should be ["a"] for the first instance you create and ["b"] for the second instance. The first instance gets deleted when you reassign "c" to the second instance. Does this make things more clear?
@dataclass
class C():
    mylist: list
    a: str
 
    def __post_init__(self):
        return self.mylist.append(self.a)
 
 
x = C("a")
print(x.mylist, x.a)
y = C("b")
print(y.mylist, y.a)
If C wasn't a dataclass, and mylist was a class variable it would do what you say,
class C():
    mylist = []

    def __init__(self, a):
        self.a = a
        self.mylist.append(a)


c = C("a")
print(c.mylist)
c = C("b")
print(c.mylist)
Or if you wanted to use dataclass and still have a class variable.
from dataclasses import dataclass


@dataclass
class C():
    a: str
    mylist = []

    def __post_init__(self):
        return self.mylist.append(self.a)


c = C("a")
print(c.mylist)
c = C("b")
print(c.mylist)
flash77 likes this post
Reply
#3
Dear deanhystad,

thanks a lot for your answer!

Second and third example works perfectly (for the first an error occurs...)

But I'm looking to be able to store strings in a list and keep it when the program ends or the pc is turned off.

Beside a text file or a dictionary I wasn't able to find something...

Perhaps I'm mistaken about dataclasses to keep data, because "common" classes can't store data.

Perhaps you could give me a hint...
Reply
#4
A dictionary will not save information after the program ends. To do that you need files. Either a file you write yourself, or a file that is maintained by a database.

Dataclasses are just a convenient way for writing classes that mostly store information. By using @datacass you get __str__ and __repr__ methods that return prettier strings than those returned by Object. A dataclass can also alutomatically generate comparison methods (__lt__, __gt__, __eq__, etc) that you can use to compare or sort instances of your class. Other than thata, dataclasses are just like any other class. They are not capable of persistent storage.

You should read about json files.
snippsat likes this post
Reply
#5
(Mar-14-2024, 04:41 PM)deanhystad Wrote: A dictionary will not save information after the program ends. To do that you need files. Either a file you write yourself, or a file that is maintained by a database.

Dataclasses are just a convenient way for writing classes that mostly store information. By using @datacass you get __str__ and __repr__ methods that return prettier strings than those returned by Object. A dataclass can also alutomatically generate comparison methods (__lt__, __gt__, __eq__, etc) that you can use to compare or sort instances of your class. Other than thata, dataclasses are just like any other class. They are not capable of persistent storage.

You should read about json files.

Okay, thanks a lot...
Have a nice evening...
Reply
#6
lash77 Wrote:Perhaps I'm mistaken about dataclasses to keep data, because "common" classes can't store data.
As mention dataclasses are just convenient way for writing classes and has no own way to store data.
A example with Json could be like this,this is serialization and other format is pickle.
This mean that get back a working Python list after data ha been saved to disk.
from dataclasses import dataclass
import json

@dataclass
class C:
    a: str
    mylist = []  # Shared among all instances

    def __post_init__(self):
        C.mylist.append(self.a)
        self.save_list()

    @classmethod
    def save_list(cls):
        with open('mylist.json', 'w') as f:
            json.dump(cls.mylist, f)

    @staticmethod
    '''This just a ordinary function placed in the class'''
    def read_list():
        with open('mylist.json', 'r') as fp:
            return json.load(fp)
Use:
>>> c = C("a")
>>> c = C("b")
>>> c.read_list()
['a', 'b']
# Or
>>> C.read_list()
['a', 'b']
Reply
#7
Thanks a lot...
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question How to append integers from file to list? Milan 8 1,457 Mar-11-2023, 10:59 PM
Last Post: DeaD_EyE
  read a text file, find all integers, append to list oldtrafford 12 3,618 Aug-11-2022, 08:23 AM
Last Post: Pedroski55
  Using .append() with list vs dataframe Mark17 7 10,535 Jun-12-2022, 06:54 PM
Last Post: Mark17
  How to append multiple <class 'str'> into a single List ahmedwaqas92 2 2,355 Jan-07-2021, 08:17 AM
Last Post: ahmedwaqas92
  How to append to list a function output? rama27 5 6,766 Aug-24-2020, 10:53 AM
Last Post: DeaD_EyE
  Append list into list within a for loop rama27 2 2,399 Jul-21-2020, 04:49 AM
Last Post: deanhystad
  Append only adding the same list again and again viraj1123 4 2,063 Jun-17-2020, 07:26 AM
Last Post: viraj1123
  Cant Append a word in a line to a list err "str obj has no attribute append Sutsro 2 2,610 Apr-22-2020, 01:01 PM
Last Post: deanhystad
  Problem with append list in loop michaelko03 0 1,688 Feb-16-2020, 07:04 PM
Last Post: michaelko03
  append list to empty array SchroedingersLion 1 2,185 Feb-02-2020, 05:29 PM
Last Post: SchroedingersLion

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020