1

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?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Fred Zimmerman
  • 1,178
  • 3
  • 13
  • 29
  • 1
    Yup, totally safe. I prefer reusing names that have short scopes, actually, because it reduces the number of different variables to keep track of when I'm reading the code; there's no way a stale value is going to unexpectedly resurface because of a typo. – Samwise Apr 05 '22 at 23:31
  • Sidenote: you don't need to explicitly close files opened using `with`. – wjandrea Apr 05 '22 at 23:33
  • 1
    Where are the functions? Maybe you mean "function calls"? Or are you referring to the `with`-`as` statements? – wjandrea Apr 05 '22 at 23:35
  • 1
    You're asking about the name `m`, right? I'm just confused why you mention that you check for successful creation of `thisdoc_dir` and `metadatas`, cause if they weren't successfully created, the lines that use them would raise exceptions (like `FileNotFoundError` and `IndexError`, respectively). – wjandrea Apr 05 '22 at 23:46

1 Answers1

1

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.

Anonymous
  • 452
  • 2
  • 9