Creating a local variable scope.

Steve Howell showell30 at
Mon Nov 30 01:46:43 CET 2009

On Nov 29, 4:26 pm, markolopa <marko.lopa... at> wrote:
> Less than 3 hours have passed since my last post and got yet another
> bug that could be prevented if Python had the functionality that other
> languages have to destroy variables when a block ends. Here is the
> code:
> =========
> arg_columns = []
> for domain in
>     i = self.get_column_index(column_names,
>     col = column_elements[i]
>     if len(col) != len(val_column):
>         ValueError('column %s has not the same size as the value
> column %s'
>                    % (column_names[i],
>         arg_columns.append(col)
> [...]
> value_dict = {}
> for i, val_str in enumerate(val_column):
>     arg_name_row = [c[i] for c in arg_columns]
>     args = [domain[name] for name in arg_name_row]
>     value_dict[tuple(args)] = float(val_str)
> repo[] = value_dict
> =========
> The bug is corrected replacing the line
>     args = [domain[name] for name in arg_name_row]
> by
>     args = [domain[name] for name, domain in zip(arg_name_row,
> so "domain" should not exist in my namespace since I have no
> information associated to "domain" only to "". Python
> should allow me to write safe code!
> Antoher 15 minutes lost because of that Python "feature"... Is it only
> me???

I occasionally make the error you make, but I think the real problem
you are having is lack of attention to detail.  If name collisions are
a common problem for you, consider writing shorter methods or develop
the habit of using more descriptive variable names.  In the code
above, you could have easily cleaned up the namespace by extracting a
method called get_arg_columns().  Having to spend 15 minutes tracking
down a bug usually indicates that you are not being systematic in your
thinking.  If you are rushing too much, slow down.  If you are tired,
take a break.  If you make the same mistake twice, commit to yourself
not to make it a third time.  Also, test your methods one at a time
and get them rock solid before writing more code.

More information about the Python-list mailing list