For practical purposes, the garbage collector cleans up at the __exit__() method, when the "local" variables are to be removed. Technically, the "with" statetment is a "try ... except ... finally"
around a context manager, which works like an object. The assignments in the "with" statement itself are considered local to that context and attached to the context manager, so they get cleaned up when the context manager is removed itself. The context manager basically has a reference to the first variable "file", but the new variable called "file" is created as a different variable as it gets reassigned.
You can't really debug this with the Python interpreter. The "with" statement is a compound statement, and those only get executed once the compound statement has been fully parsed. If you have a Linux system it would look a bit like this
Python:
#!/bin/env python3
import os
import sys
import subprocess
with open('test.txt', 'r') as file:
print(type(file))
print(sys.getrefcount(file))
os.system('ls -al /proc/%d/fd' % os.getpid())
file = file.read()
print(type(file))
print(sys.getrefcount(file))
os.system('ls -al /proc/%d/fd' % os.getpid())
os.system('ls -al /proc/%d/fd' % os.getpid())
This would output something like this:
Code:
<class '_io.TextIOWrapper'>
3
total 0
dr-x------ 2 user user 0 Jun 23 15:45 .
dr-xr-xr-x 9 user user 0 Jun 23 15:45 ..
lrwx------ 1 user user 64 Jun 23 15:45 0 -> /dev/pts/13
lrwx------ 1 user user 64 Jun 23 15:45 1 -> /dev/pts/13
lrwx------ 1 user user 64 Jun 23 15:45 2 -> /dev/pts/13
lr-x------ 1 user user 64 Jun 23 15:45 3 -> /home/user/test.txt
2
<class 'str'>
total 0
dr-x------ 2 user user 0 Jun 23 15:45 .
dr-xr-xr-x 9 user user 0 Jun 23 15:45 ..
lrwx------ 1 user user 64 Jun 23 15:45 0 -> /dev/pts/13
lrwx------ 1 user user 64 Jun 23 15:45 1 -> /dev/pts/13
lrwx------ 1 user user 64 Jun 23 15:45 2 -> /dev/pts/13
lr-x------ 1 user user 64 Jun 23 15:45 3 -> /home/user/test.txt
total 0
dr-x------ 2 user user 0 Jun 23 15:45 .
dr-xr-xr-x 9 user user 0 Jun 23 15:45 ..
lrwx------ 1 user user 64 Jun 23 15:45 0 -> /dev/pts/13
lrwx------ 1 user user 64 Jun 23 15:45 1 -> /dev/pts/13
rrwx------ 1 user user 64 Jun 23 15:45 2 -> /dev/pts/13
Python is not even my main job, but I still have to work with so much old Python 2 code, that my brain basically mixed and blended everything together in one big "Python" pile.