News for hackers. Stuff that matters.
Re:I'm Switching to Python and Actually Liking It by nomel on Thursday July 17, 2025 @12:56AM (#44589817)
Are you saying that this should result in a name error?

   if <true comparison here>:
       x = 5
   print(x)  # <- should give name error?
Re:I'm Switching to Python and Actually Liking It by suspended_state on Thursday July 17, 2025 @02:43AM (#44590416)
I stand corrected, the exception case is definitely an oddity, both as being an outlier and as a strange behaviour wrt Python's semantics. Or is it a strange behaviour?

In the case of an if like in your example, no provision is made about the existence of x. It could have been defined earlier, and this line would simply update its value.

Your example:

   if True:
       x = 5
   print(x)  # 5

Same with x defined prior:

   x = 1
   if False:
       x = 5
   print(x)  # 1
What about this one?

   if False:
       x = 5
   print(x)  # ???


On the other hand, the notation "<exception value> as <name>" looks like it introduces a new name; what if that name already existed before? Should it just replace the content of the variable? Why the "as" keyword then? Why not something like "except <name> = <exception value>" or the walrus operator?

While investigating this question, I tried the following:

    x = 3
    try:
        raise Exception()
    except Exception as x:
        pass
    print(x)  # <- what should that print?
Re:I'm Switching to Python and Actually Liking It by fc417fc802 on Friday July 18, 2025 @12:56AM (#44601347)
In any sane language it would, yes.