2 ms·
While the walrus operator gives a way to see this sort of non-C++ behavior, it's more showing that Python isn't C++ than something special about the operator.
by eesmith 5y ago
While the walrus operator gives a way to see this sort of non-C++ behavior, it's more showing that Python isn't C++ than something special about the operator.
Here's another way to trigger the same NameError, via "global":
import random
def foo():
return random.randrange(2)
def bar():
global w
w = return random.randrange(20)
return w
while foo() or (bar() < 10):
print(w)
For even more Python-is-not-C++-fun:
import re
def parse_str(s):
def m(pattern): # I <3 Perl!
nonlocal _
_ = re.match(pattern, s)
return _ is not None
if m("Name: (.*)$"):
return ("name", _[1])
if m("State: (..) City: (.*)$"):
return ("city", (_[2], _[1]))
if m(r"ZIP: (\d{5})(-(\d{4}))?$"):
return ("zip", _[1] + (_[2] if _[2] else ""))
return ("Unknown", s)
del _ # Remove this line and the function isn't valid Python(!)
for line in (
"Name: Ernest Hemingway",
"State: FL City: Key West",
"ZIP: 33040",
):
print(parse_str(line))
- dataflow 5y agoRight, I'm quite well-aware of that, but I'm saying this change has made the situation even worse. If they ensured the variables were scoped and actually initialized it'd have actually been an improvement.
- eesmith 5y agoI apologize. I misinterpreted your comment: # w is in-scope here, but possibly nonexistent! # Even in C++ it would at least *exist*! because I don't see how bringing up C++'s semantics is relevant when Python has long raised an UnboundLocalError for similar circumstances. If I understand you correctly, you believe Python should have introduced scoping so the "w" would be valid only in the if, elif, and else clauses, and not after the 'if' ends. This would be similar to how the error object works in the 'except' clause: >>> try: ... 1/0 ... except Exception as err: ... err = "Hello" ... >>> err Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'err' is not defined If so, I do not have the experience or insight to say anything meaningful.