How to fix RecursionError: maximum recursion depth exceeded

1.8k Views Asked by At

Here's the question:

07. Define a function named import_zip_codes_json() which imports the zip_codes.json as a list in working directory.

Here's the code:

import json
with open('zip_codes.json') as list:
  zip_codes_json = json.load(list)

(The 'def' line is defined by teacher, and what I've wrote is the below part.)

def import_zip_codes_json() -> list:

    zip_codes_json = import_zip_codes_json()
    return zip_codes_json

type(zip_codes_json)

I got 'list' for my return, and it's right. But after running all the codes, I've got RecursionError.

ERROR: test_07_import_zip_codes_json (__main__.TestMidterm)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython-input-524-ba9f8f20ec9d>", line 48, in test_07_import_zip_codes_json
    zip_codes_json = import_zip_codes_json()
  File "<ipython-input-516-0c2ae51a67d5>", line 10, in import_zip_codes_json
    zip_codes_json = import_zip_codes_json()
  File "<ipython-input-516-0c2ae51a67d5>", line 10, in import_zip_codes_json
    zip_codes_json = import_zip_codes_json()
  File "<ipython-input-516-0c2ae51a67d5>", line 10, in import_zip_codes_json
    zip_codes_json = import_zip_codes_json()
  [Previous line repeated 941 more times]
RecursionError: maximum recursion depth exceeded

I've searched on Google for solutions, and I've tried to use sys.setrecursionlimit(20000)

import sys
sys.setrecursionlimit(20000)

but I still got RecursionError

ERROR: test_07_import_zip_codes_json (__main__.TestMidterm)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython-input-562-ba9f8f20ec9d>", line 48, in test_07_import_zip_codes_json
    zip_codes_json = import_zip_codes_json()
  File "<ipython-input-554-0c2ae51a67d5>", line 10, in import_zip_codes_json
    zip_codes_json = import_zip_codes_json()
  File "<ipython-input-554-0c2ae51a67d5>", line 10, in import_zip_codes_json
    zip_codes_json = import_zip_codes_json()
  File "<ipython-input-554-0c2ae51a67d5>", line 10, in import_zip_codes_json
    zip_codes_json = import_zip_codes_json()
  [Previous line repeated 19941 more times]
RecursionError: maximum recursion depth exceeded

How can I fix this?

1

There are 1 best solutions below

2
John Gordon On
def import_zip_codes_json() -> list:

    zip_codes_json = import_zip_codes_json()
    return zip_codes_json

The first thing import_zip_codes_json() does is call itself, which then calls itself, which then calls itself.... forever. Or until the stack blows up and you get the error.

Why are you doing this?