Why did Python3 execute a piece of commented-out code?

Viewed 799

After a bit over 8 years of using Python I've run today into issue with Python 3.8: it executed code that I commented out.

I was able to interrupt it as it was going through code path that should have been blocked by the comment to get this screenshot:

enter image description here

As the function names indicate, the operation in question is somewhat time-consuming to rollback and I would love to know what happened to avoid dealing with that in the future.

My current best explanation is that since the code is run on a remote machine for whatever reason the commenting out did not go through when the code started, but did for the stack trace.

Does anyone had a similar experience or have an idea of what might have happened?

1 Answers

I confirmed my hypothesis from the comments, with a file like:

import time

def dont_run():
  raise Exception("oh no i ran it")

time.sleep(10)

dont_run()

I saved that file, and ran it. While it was running I commented out the last line and re-saved the file, I then got this error:

$ py main.py
Traceback (most recent call last):
  File "main.py", line 10, in <module>
    # dont_run()
  File "main.py", line 6, in dont_run
    raise Exception("oh no i ran it")
Exception: oh no i ran it

So I think what must have happened here is that you ran the file before the file was saved to disk (perhaps a race between two network requests and you got unlucky).

Related