[python] Conditionally apply ContextManager cleanup logic
#4426
+57
−6
ContextManager cleanup logic
#4426