0

I face with unexpected link to one same object in different objects , while condition isn't works. So there are 3 objects:

c1, c2, c3 = C(1, 'name1'), C(2, 'name2'), C(3, 'name3')

they have next fields and interface:

class C:
    def __init__(self, c_id:int, c_name:str, b:List=[]):
        self.c_id:int= c_id:int
        self.c_name:str= c_name:str
        self.b= b
        self.cs= []

    def _check_c(self, c_id:int):
        self.c = [i.c_id for i in self.b]
        self.b.sort(reverse=True, key= lambda c: c.c_id)
        if c_id in self.cs:
            return True
        else:
            return False

To fill C objects i will use Collector class:

class Collecter:

    def __init__(self, data:List[Any]):
        self.data = data

    async def fill_c(cs:List[C], data)->List:
            for d in  data:
                try:
                    if d[0] and d[0].__len__()>=10:

                        c_num = d[0][4]
                        c = cs[int(c_num)-1]
                        if int(c_num) == c.c_id:

                            if c.b.__len__()<1 or not c._check_c(d[1]):

                                c.b.append(B(d[2], d[1]))
                                b = c.b[0]
                                m = (d[3], d[4])
                                b.ms.append(m)

                            else:

                                b = c.b[0]
                                m = (d[3], d[4]) 
                                b.ms.append(m)

                    else:
                        pass
                except Exception as ex:
                    raise ex
            
            return cs

and every time, whe i am going to try init and run:

c1, c2, c3 = await Collecter.fill_c([c1, c2, c3], self.data)

even if first condition (if) code block is not (it means that was appened nothing), my objects have one same object in filed: enter image description here

I really don't understand why I face it. PS code called from FastAPI REST

UPD data is List[sqlalchemy.engine.row.LegacyRowsqlalchemy.engine.row.LegacyRow]

Tyomik_mnemonic
  • 786
  • 3
  • 9
  • 31

1 Answers1

1

So, you could be confused hardy when you use mutable objects as a default value of argument in your methods. There is the best explanation .

Tyomik_mnemonic
  • 786
  • 3
  • 9
  • 31