A desperate lunge for on-topic-ness

Chris Angelico rosuav at gmail.com
Mon Oct 22 03:03:39 EDT 2012


On Mon, Oct 22, 2012 at 5:30 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> For languages without static types, what other reasons for declaring
> variables are there?

The main one is scope nesting. Compare a few different languages.

Python: If you don't declare, it's global if you don't rebind it, but
local if you do. You may declare variables as global or nonlocal.

PHP: If you don't declare, it's local, but functions are in a separate scope.

C: If you don't declare, it's looked for in some broader scope. If
it's not declared in any scope, error.

All three approaches make reasonable sense. The PHP one is perfectly
consistent, but would be hopelessly impractical if all your function
names had to be marked off as globals. (Plus PHP has superglobals,
with their own Marvellous mess.) Python's system "just works" most of
the time, but can introduce yet another trap for the unsuspecting
newbie who doesn't understand the difference between rebinding and
mutating; I've not looked into multiple levels of closures but I
suspect there'll be odd limitations there, as there's only one
"nonlocal" keyword. The C style has administrative overhead (requiring
explicit declarations for all variables), but allows full flexibility
(variables having narrower scope than entire functions, infinite
nesting of scopes, etc).

Incidentally, variable declarations don't have to be connected with
static typing. JavaScript/ECMAScript simply has 'var x;' to declare
that x exists in this function. But it's hardly a language that I'd
hold up as a shining example; a var declaration anywhere in a function
makes that variable name local to that entire function. There's
actually no block scoping at all. And then there's the whole confusion
of the global object, 'this', and 'with' statements...

You knew I was going to cite it sooner or later :) Pike has true block
scoping, though unlike C++, Pike does not guarantee that destructors
will be called immediately at the close brace (but zero-reference
objects will be cleaned up, including destructor calls, at the next
function return - even if not the current function). Variables can be
mostly-statically-typed, or can be declared as 'mixed' and be rebound
freely (like in JS and Python). So scoped variable declarations and
static typing are quite orthogonal.

ChrisA



More information about the Python-list mailing list