0

I have the init_sale variable but when calling a method that has nothing to do with the variable, it changes the variable value

Class Code

def get(self, nro_order):
    
    order = Order().get_by_order(nro_order)
    if order is None:
            nro_order)
            )
        return None

    init_sale = self.get_init_sale(nro_order) #this change after call calculate sale
    nationalized = self.get_nationalized(order)

    data = {
        'init_sale': init_sale,
        'nationalized': nationalized,
        'sale': self.calculate_sale(init_sale, nationalized)
    }
    return data

def calculate_sale(self, init_sale, nationalized):
        sale = init_sale
        for item in sale:
            for nat in nationalized:
                if item['detalle_pedido_factura'] == nat['detalle_pedido_factura']:
                    item['nro_cajas'] -= nat['nro_cajas']
        return sale

init_sale before call calculate_sale:

[{'detalle_pedido_factura': 1164, 'cod_contable': '01011080050317010750', 'nro_cajas': 1145, 'costo_caja': 18.5}]

init_sale after call calculate_sale:

[{'detalle_pedido_factura': 1164, 'cod_contable': '01011080050317010750', 'nro_cajas': 0, 'costo_caja': 18.5}]

nro_cajas value change

Thanks

eduardouio
  • 13
  • 4
  • Does this answer your question? [List changes unexpectedly after assignment. How do I clone or copy it to prevent this?](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-how-do-i-clone-or-copy-it-to-prevent) – 9bO3av5fw5 Dec 30 '20 at 21:10

2 Answers2

0

According to your code, your method calculate_sale is substracting nro_cajas to itself : ‘item['nro_cajas'] -= nat['nro_cajas']‘

When you did : ‘sale = init_sale‘ You did not create a new instance of your dict, you just point toward it thru the "sale" variable.

You should do : ’sale = init_sale.copy()’

Romk
  • 91
  • 5
  • Thank friend!, but not works 'costo_caja': 18.5} {'cod_contable': '01011080050317010750', 'costo_caja': 18.5, 'detalle_pedido_factura': 1164, - 'nro_cajas': 1176} ? ^^^^ + 'nro_cajas': 0} ? ^ – eduardouio Dec 30 '20 at 22:38
  • Judging by your solution, I'm not shure I clearly understood your question... ;-) – Romk Dec 31 '20 at 14:09
0

im solved this problem, but i think it is not correct way

    def calculate_sale(self, init_sale, nationalized):
    sale = [] #create empty list
    for itm in init_sale: #append items :(
        sale.append({
            'detalle_pedido_factura': itm['detalle_pedido_factura'],
            'cod_contable': itm['cod_contable'],
            'nro_cajas': itm['nro_cajas'],
            'costo_caja': itm['costo_caja'],
        })
    for item in sale:
        for nat in nationalized:
            if item['detalle_pedido_factura'] == nat['detalle_pedido_factura']:
                item['nro_cajas'] -= nat['nro_cajas']
    return sale
eduardouio
  • 13
  • 4