Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

is it safe to use the same variable name repeatedly in a series of functions?

Is it safe to re-use the same variable name repeatedly in a series of functions? My code is:

with open(thisdoc_dir + '/' + 'metadata.txt', 'w') as m:
    m.write(str(metadatas[1]) + '\n')
    m.close()
    
with open(thisdoc_dir + '/' + 'metadata.json', 'w') as m:
    m.write(str(metadatas[0]))
    m.close()
    
with open(thisdoc_dir + 'toc.txt', 'w') as m:
    m.write(str(metadatas[2]))
    m.close()

Before this block, I try/except to test for successful creation of thisdoc_dir and metadatas. Is there anything else that can be a gotcha?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

These aren’t functions, but rather context managers. Regardless, m is local, and even if it wasn’t, it would be overridden. Also, since you are using with, you don’t need to manually close the file afterwards.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading