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)
m.brindley
  • 1,218
  • 10
  • 19
Chirdeep Tomar
  • 4,281
  • 8
  • 37
  • 66

1 Answers1

3

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

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • 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() – Chirdeep Tomar Feb 02 '13 at 00:33
  • 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 - http://stackoverflow.com/questions/2192926/using-explicit-del-in-python-on-local-variables – m.brindley Feb 02 '13 at 01:16