fleetC0m
fleetC0m

Reputation: 251

Python does not warn about variable re-declaration

I just spent a whole day tracking down this bug:

for idx, val in enumerate(some_list):
    for idx, otherval in enumerate(another_list): #the idx for the outer loop is overwritten
        #blah blah

Coming from a strongly typed language background, I got bitten hard by this. In strongly typed languages I would get an error about variable re-declaration. I don't know why the interpreter doesn't issue a warning for this, and the design decision behind this. This is obviously a bug, I mean, what could possibly be the legit use of this construct? Is there any option to enable this sort of check? Thanks.

Upvotes: 2

Views: 89

Answers (2)

Scott Lawrence
Scott Lawrence

Reputation: 1073

There's no way to enable this sort of check. Ordinarily I'd recommend using a linting tool, but pylint (my favorite) doesn't seem to notice this, and neither does pychecker.

As for rationale: you want to allow stuff like

a = 1
a = 2

Ok, so how about

a = ""
a = 1

Well that should probably be ok too. Now what about

a = 1
for a in range(5):

You see the problem? It's not really that clear what should be an error/warning and what shouldn't.

(I admit I would like this thing to be caught by a tool like pychecker, and I'm a little disappointed.)

Upvotes: 4

aknuds1
aknuds1

Reputation: 67997

This is how Python works, you are free to redefine variables. If you expect it to behave like a statically typed language, you're only in for disappointment.

Upvotes: 2

Related Questions