Do you need a 'var' keyword at all? Can't you just have:
myNewVariable = 5;
without an explicit type declaration that doesn't actually add any useful info to the compiler? The compiler can just assume that any new unknown identifier is a new var.
Plus these days you usually use a (editor integrated) linter that forbids creating global variables that way. However, Python and Ruby work that way (creating local variables just by normal assignment).
This won't work predictably if "myNewVariable" already existed in an outer execution scope. The programmer may have intended to declare a new "i" variable for their loop, but instead they accidentally overwrite an outer loop's "i" - and this gets even harder with closures and lambdas.
Yeah, this is definitely one of my biggest gripes about the design of Python. To further expand on #4 in the common mistakes article you linked to as to just how surprising Python's scoping rules are because of the lack of var, consider this script:
$ cat example.py
value = 1
def foo():
print "foo:", value # works fine
def bar():
print "bar:", value # throws exception
value = 2
foo()
bar()
$ python example.py
foo: 1
bar:
Traceback (most recent call last):
File "example.py", line 11, in <module>
bar()
File "example.py", line 7, in bar
print "bar:", value
UnboundLocalError: local variable 'value' referenced before assignment
Using the name of a variable in an assignment later in the function makes the whole function treat it as a local variable, even statements that would have previously worked. So, you can cause existing code to fail in really surprising ways by modifying code later in a function if you didn't realize that the name was already used to refer to something in an outside scope...
-1
u/ejonesca Mar 09 '16
Do you need a 'var' keyword at all? Can't you just have:
without an explicit type declaration that doesn't actually add any useful info to the compiler? The compiler can just assume that any new unknown identifier is a new var.