1

in the code here How do I force static methods to use local not global variables in Python?

i have a variable that is being passed between methods besides the one in the question. the variable is current_line

def line_tocsv(csv_dict={}, line={}, current_line=0):
    csv_line, current_line = LineHandler.create_csv(current_line, kline)
    if current_line in csv_dict:
        csv_dict[current_line].update(csv_line)
    else:
        csv_dict[current_line] = csv_line 
    return csv_dict

when this code is run, it produced an output simmilar to this

>>> a={0:{"aa":1,"bb":"wasd"},1:{"aa":1,"bb":"wasd"}} 
>>> a
{0: {'aa': 1, 'bb': 'wasd'}, 1: {'aa': 1, 'bb': 'wasd'}}
>>> a[1].update({"cc":"foo"})
>>> a
{0: {'aa': 1, 'cc': 'foo' 'bb': 'wasd'}, 1: {'aa': 1, 'cc': 'foo', 'bb': 'wasd'}}

how do i make it so that the csv_line dict is only entered into ONE sub dict?! changing the variable names does not work and i suspect it is because only the references are passed between functions, but i dont know enough python to know where those references actually go and what their order of ops etc is

Community
  • 1
  • 1
tenshiism
  • 57
  • 1
  • 5
  • 2
    Possible duplicate of ["Least Astonishment" in Python: The Mutable Default Argument](http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument) – Łukasz Rogalski Feb 08 '16 at 08:01
  • this is not because i put the var in the variable as (`var=0`) i already changed it to just `(var)` and checked that it was equal to 1 in the scope of the function by print and in eclipse. besides, how can the dict be updated TWICE in ONE line? – tenshiism Feb 08 '16 at 08:04

1 Answers1

1

First, don't use mutable default arguments

def line_tocsv(csv_dict=None, ....):
    if not csv_dict:
        csv_dict = {}
    ....

Next, use copy of dict, not pointer:

csv_dict[current_line] = csv_line.copy()

EDIT:

Try to do this:

>>> a
{1: 2, 3: 4}
>>> b = {1:a,2:a}
>>> b
{1: {1: 2, 3: 4}, 2: {1: 2, 3: 4}}
>>> b[1][7] = 8
>>> b
{1: {1: 2, 3: 4, 7: 8}, 2: {1: 2, 3: 4, 7: 8}}

If you want to use value of dict instead of pointer:

>>> a
{1: 2, 3: 4}
>>> b = {1:a.copy(),2:a.copy()}
>>> b
{1: {1: 2, 3: 4}, 2: {1: 2, 3: 4}}
>>> b[1][7] = 8
>>> b
{1: {1: 2, 3: 4, 7: 8}, 2: {1: 2, 3: 4}}
Alexey Astahov
  • 203
  • 1
  • 7
  • well it kinda worked... but it seems to make the last couple of dicts the same.. i havnt checked yet because i have to decode from utf but looking at the utf codes they seem to be different except the last two entries – tenshiism Feb 08 '16 at 09:01