I’m trying to add some manual garbage collection at the end of my script, but for some reason when I iterate through dir()
it is still picking up names that start with "blob"
even though I’ve tried to specify not to do so. Reason for doing so is that trying to delete dataframes through del globals()[name]
causes errors. What am I doing wrong here?
#Initializing data frames
blob_data_frame = None
blob_data_frame1 = None
blob_data_frame2 = None
...
del blob_data_frame # This one will always not be None
if blob_data_frame1 is not None:
del blob_data_frame1
if blob_data_frame2 is not None:
del blob_data_frame2
for name in dir():
if not name.startswith('_') or not name.startswith('blob'): <- PROBLEM
del globals()[name]
for name in dir():
if not name.startswith('_') or not name.startswith('blob'):
del locals()[name]
>Solution :
The issue is that you want to delete all variables where the name does not start with "_"
, AND the name does not start with "blob"
. However, your code is deleting variables where the names do not start with "_"
OR names that do not start with "blob"
.
The difference between the "and" and the "or" is significant here. In the "and" case, the variable name has to meet both conditions. In the "or" case, though, the variable name can meet either OR both conditions – meaning that if the variable starts with "_"
, for example, then that means it doesn’t start with "blob"
, so the if
statement would evaluate to True
.
Example:
not startswith("_") OR not startswith("blob"):
startswith("_")
-> True
startswith("blob")
-> False
-> not True OR not False
-> False OR True
-> True
not startswith("_") AND not startswith("blob"):
startswith("_")
-> True
startswith("blob")
-> False
-> not True AND not False
-> False AND True
-> False