Question

In this piece of code, if I match the given pattern on the line, I replace the line by a self-built string. Is this actually good practice? It looks a little bit like reusing the variable line for output, where it actually contains the contents of the currently read line.

for line in lines:
  match = re.search(r'@Table\(name = "(.*)"\)', line)

  if match:
    line = "".join(['@Table (name = "', prefix, match.group(1)[:max_len], '")', '\n'])

  f.write(line)

f.close()
Was it helpful?

Solution

I'd say the intent in your code is clear and the code is short and simple so there is nothing wrong in it. If it still bothers you to be reusing the variable, you can do something like this:

for line in lines:
    match = re.search(r'@Table\(name = "(.*)"\)', line)

    if match:
        output_line = "".join(['@Table (name = "', prefix, match.group(1)[:max_len], '")', '\n'])
    else:
        output_line = line

    f.write(output_line)

f.close()

This way, each variable name describes exactly its contents all of the time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top