Creating a local variable scope.

Dave Angel davea at ieee.org
Sun Nov 29 22:46:42 EST 2009


markolopa wrote:
> <snip>
> =======
>
> arg_columns =]
> for domain in self.domains:
>     i =elf.get_column_index(column_names, domain.name)
>     col =olumn_elements[i]
>     if len(col) !=en(val_column):
>         ValueError('column %s has not the same size as the value
> column %s'
>                    % (column_names[i], self.name))
>         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)] =loat(val_str)
> repo[self.name] =alue_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,
> self.domains)]
>
> so "domain" should not exist in my namespace since I have no
> information associated to "domain" only to "self.domains". Python
> should allow me to write safe code!
>
> Antoher 15 minutes lost because of that Python "feature"... Is it only
> me???
>
>   
Yep, I think so.  You're proposing a much more complex scoping rule, 
where if a variable already exists before entering a loop, then the loop 
uses that existing variable, but if not, it creates its own local one 
and destroys it when exiting the loop.  That's the exact opposite of 
what function definitions do, which already makes it confusing.

I think if you had your wish, you'd find that you had more exceptions 
where you had to pre-declare things, than the times when you avoided the 
bugs you describe.  I don't like languages that make me write extra 
stuff 100 times, to save one instance of extra debugging.  If Python 
already required declarations, then I might buy your arguments.  But it 
wouldn't be Python.
> Thanks for your comment!
> Marko
>
>   

In your particular case, the compiler couldn't guess whether you used 
the first loop to decide which domain to use in the second loop, or 
whether you accidentally reused the same name without giving it a new 
value in the new loop.  If you need to use the same name, you could 
always follow your loops with the del statement to invalidate the name.


DaveA




More information about the Python-list mailing list