Search code examples
pythonpickle

Why am I getting this error: RecursionError: maximum recursion depth exceeded while pickling an object


I was creating an infinitely looping problem (just for fun), but I encountered this error: "RecursionError: maximum recursion depth exceeded while pickling an object" following this message:

Traceback (most recent call last):
  File "<pyshell#34>", line 2, in <module>
    exec(p.read())
  File "<string>", line 6, in <module>
  File "<string>", line 6, in <module>
  File "<string>", line 6, in <module>
  [Previous line repeated 503 more times]
  File "<string>", line 4, in <module>
RecursionError: maximum recursion depth exceeded while pickling an object

I did not import the pickling module, and I don't know why this error is occurring.

I ran this code in the Python interpreter:

with open("Cool.py", "a")as p1:
    p1.write("""for _ in range(10):\n\t""")
    p1.write("""with open("Cool.py" "r")as p1:\n""")
    p1.write("""\t\tfor b in p1:\n""")
    p1.write("""\t\t\tprint(b)""")

I already have an empty .py file called "Cool.py" in my documents folder (I'm a Mac user). After I run the above code, I run this code to call the file without having to open it:

with open("Cool.py") as p:
    exec(p.read())

I know it's lazy, but I'm mainly just curious why it came up with the pickle module. Can anybody explain why I'm getting the error (and how to fix it--although that's less important).


Solution

  • With your first five lines of code, it opens the file cool.py and writes the following.(Please note that in the line p1.write("""with open("Cool.py" "r")as p1:\n"""), you have omitted the comma. It is supposed to be p1.write("""with open("Cool.py", "r")as p1:\n""") Also I added \n in the last line to see what happens.

    **#assume this is code_1**
    for _ in range(10):
        with open("Cool.py", "r")as p1:
            for b in p1:
                print(b)
    

    Now you are executing the following lines of code:

    **#Assume this is code_2**
    with open("Cool.py") as p:
        exec(p.read())
    

    with the code exec(p.read()) you are asking to execute the read code. That is the code_1 will be executed as python code(See my comment to know what is code_1). Here you've asked to open the same file ten times. But, Here it's not over.

    Everytime, the file is opened, the code_2 executes the code_1 in the file as it is with open (Hidden Meaning: if it is opened, then execute the code inside.) And each time it needs to open the same file 10 times, and each time when it is opened, the code is executed. It's a never ending process.

    Though the purpose of with open is meant to avoid closing the file each time, this is how it behaves.

    A better way to reduce the complication is: Write a code which writes a function in the file. Import it and run the function.