[New-bugs-announce] [issue13678] way to prevent accidental variable overriding

James Hutchison report at bugs.python.org
Thu Dec 29 20:08:39 CET 2011

New submission from James Hutchison <jamesghutchison at gmail.com>:

In python is currently there a way to elegantly throw an error if a variable is already in the current scope?

For example:

def longfunc(self, filename):
    FILE = open(filename);
    header = FILE.readline();
    ... bunch of code ...
    childfiles = self.children;
    for child in childfiles:
         FILE = open(child);
         header = FILE.readline();
         ... do something with header ...
    for line in FILE:
       ... etc ...

In this case, I'm accidentally overriding the old values of FILE and header, resulting in a bug. But I'm not going to catch this. I've had a couple of real life bugs due to this that were a lot more subtle and lived for months without anyone noticing the output data was slightly wrong.

This situation could be prevented if there was a way to say something along the lines of "new FILE = open(child)" or "new header = FILE.readline()" and have python throw an error to let me know that it already exists. This would also make code clearer because it allows the intended scope of a variable to become more apparent. Since "new var = something" is a syntax error, adding this functionality wouldn't break old code, as long as python would allow for 'new' (or whatever the keyword would end up being) to also be a variable name (like "new new = 1" or "new = 1")

components: Interpreter Core
messages: 150344
nosy: Jimbofbx
priority: normal
severity: normal
status: open
title: way to prevent accidental variable overriding
type: enhancement
versions: Python 3.2, Python 3.3, Python 3.4

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list