0

I am confused howcome the variable temp_dict is available outside else condition? when I am saving the array to MongoDB which is setting the ObjectId on each item in the array. Json parser doesn't doesn't know how to serialize ObjectId.

def read_temporary_file(filename, has_header=False):
    wb = load_workbook(filename=filename, use_iterators=True)
    ws = wb.get_active_sheet()  # ws is now an IterableWorksheet

    headers = []
    rows = []
    documents = []

    for row in ws.iter_rows():  # it brings a new method: iter_rows()
        if has_header:
            has_header = False
            for cell in row:
                headers.append(cell.internal_value)
        else:
            temp_dict = OrderedDict()
            for cell in row:
                temp_dict[cell.column] = cell.internal_value
            rows.append(temp_dict)
            documents.append(temp_dict)

    print("Saving documents to MongoDB")
    __save(documents)
    print("Printing %s" % temp_dict)
    return (headers, rows)
0

1 Answer 1

3

In Python, the entire function is the scope. Clauses like your else are not new scopes.

Sign up to request clarification or add additional context in comments.

2 Comments

That is just weird...so basically wait for the GC to collect the function resources then it gets disposed. Any ideas on how to solve this without creating another OrderedDict()
Scoping conditional blocks would render them almost useless - code would be covered in nonlocal definitions. You can always do del temp_dict but that's what the GC is for. Alex has a good blurb on the use of del here - stackoverflow.com/questions/2192926/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.