__del__ is called explicitly¶
ID: py/explicit-call-to-deleteKind: problemSecurity severity: Severity: warningPrecision: very-highTags: - quality - reliability - correctnessQuery suites: - python-security-and-quality.qls
Click to see the query in the CodeQL repository
The__del__ special method is designed to be called by the Python virtual machine when an object is no longer reachable, but before it is destroyed. Calling a__del__ method explicitly may cause an object to enter an unsafe state.
Recommendation¶
If explicit clean up of an object is required, aclose() method should be called or, better still, wrap the use of the object in awith statement.
Example¶
In the first example, rather than close the zip file in a conventional manner, the programmer has called__del__. A safer alternative is shown in the second example.
defextract_bad(zippath,dest):zipped=ZipFile(zippath)try:zipped.extractall(dest)finally:zipped.__del__()defextract_good(zippath,dest):zipped=ZipFile(zippath)try:zipped.extractall(dest)finally:zipped.close()
References¶
Python Standard Library:object.del