[Tutor] Appropriate use of None
Manprit Singh
manpritsinghece at gmail.com
Sat Jan 1 06:48:34 EST 2022
Dear Sir,
Consider an example of reading a file, along with exception handling in the
below given way:
file = None
try:
file =open("filefortest.txt")
text = file.read()
except IOError:
print("File can't be read")
else:
print(text)
finally:
if file != None:
file.close()
print("File is closed")
Here I have assigned None to a variable file in the beginning. Then in try
block
the file object is assigned to the same variable file. This is done so to
make the variable "file" available in finally block holding a value "None"
when an exception
is raised in the try block while reading the file.
Kindly comment if this kind of practice should be done or not ?
Regards
Manprit Singh
More information about the Tutor
mailing list