tenshiism February 2016

How do I find out if a integer variable in python has an out of scope hidden value?

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

Answers


Alexey Astahov February 2016

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}}

Post Status

Asked in February 2016
Viewed 3,890 times
Voted 14
Answered 1 times

Search




Leave an answer