problem with variable scoping
Tim Peters
tim_one at email.msn.com
Thu May 27 00:56:58 EDT 1999
[Michael Dingler]
> I'd certainly like to hear them. I'd like to know how other languages
> handle this. Doesn't Perl do it the other way round, i.e. a _local_
> keyword?
Perl started life with dynamic scoping and grafted on sensible semantics
later <0.5 wink -- but "my" rather than "local" is almost always want you
want to use in Perl5>).
Python's local rules will make instant sense to the C part of your brain if
you consider that Python acts exactly like C does, except that there's no
local *declaration* kicking you in the face.
> last_line_empty = 0
> .
> .
> .
> def process(line):
> ...
> if last_line_empty:
> pass
> else:
> print "<P>"
> last_line_empty = 1
C:
int last_line_empty = 0;
void process(const char* line)
{
int last_line_empty;
if (last_line_empty)
;
else
printf("<P>\n");
last_line_empty = 1;
}
In C too, the local last_line_empty shadows the global one, and the code is
nonsense as a result. Because it has no type declarations, Python has to
use *some* rule to decide which names are local (and happens to use a rule
based on whether a name is bound in the function body), but having made that
decision acts the same way as C. Well, not quite: Python yells at you if
you reference an uninitialized local, while C entertains you in creative
ways <wink>.
it's-a-feature-and-a-dessert-topping-ly y'rs - tim
More information about the Python-list
mailing list