Cleaning: `with` statement can save your life
s = open(path_for_saving+"host_star_properties.txt", "w") star_params = "star_id,mass_star,radius_star,age,Lbol,Lx_age\n"\ + self.star_id + "," + str(self.mass_star) + ","\ + str(self.radius_star) + "," + str(self.age)\ + "," + str(self.Lbol/const.L_sun.cgs.value)\ + "," + str(self.Lx_age) s.write(star_params) s.close()
this is dangerous, because if you get an
Error in the computation of
star_params and you catch the Error the code won't close the file before the program stops. That is harmless as long as you have one file, wait to have 100, 1000 of files. All opened together, your laptop won't like it.
To prevent that you there were the old-fashion way (don't do it it is just to understand):
s = open(...) try: star_params = compute(...) s.write(star_params) except ValueError as exception: # LOG WARNING, ERROR What ever you want raise exception finally: s.close()
This construction guaranty that even if you got an exception in the
compute function the statement in
finally will be called. That guaranty that the file will be closed what ever happens.
However this formulation was quite wordy and since python 2.x (what ever version, a long time ago anyway) the python developers added the
with open(...) as s: # compute
is equivalent to:
s = open(...) try: s.__enter__() # compute except: # treat exception finally: s.__exit__()
s is a
File.__enter__() does nothing fancy, but
File.__exit__() is nothing else than
File.close() so you see much easier and shorter to use
with and you get a full bench of improvements.