Creating a local variable scope.

markolopa marko.loparic at gmail.com
Sun Nov 29 19:26:51 EST 2009


Hi Lie!

On Nov 29, 11:11 pm, Lie Ryan <lie.1... at gmail.com> wrote:
> here is another bug you might have if python have an "even-more-local"
> scope:
>
> while True:
>      s = raw_input("enter something: ")
>      if s not in ('q', 'quit', 'exit'): break
> print s
>
> if the while block has become its own namespace; print s would generate
> NameError.

This bug you show is completely different, because it is not
dangerous: you get the error and you realise directly how to fix it.

> It is one or the other, you will have problem caused by "namespace too
> small" or "namespace too big". Neither is better than the other, so
> python's two-level name resolution (global and local level) is the
> simplest one, is the better one.

I would be much happier with the smaller namespace. To fix the code
that you show I would impose

s = None
while True:
     s = raw_input("enter something: ")
     if s not in ('q', 'quit', 'exit'): break
print s

The use in a block of variables created in an inner block is (for me
at least) more an exception than a rule.

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 self.domains:
    i = self.get_column_index(column_names, domain.name)
    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], 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)] = float(val_str)
repo[self.name] = 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,
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???

Thanks for your comment!
Marko



More information about the Python-list mailing list