Search code examples
pythontry-exceptvariable-names

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?


Solution

  • These aren't functions, but rather context managers. Regardless, m is overridden each time. Also, since you are using with, you don’t need to manually close the file afterwards.