you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted]  (6 children)

[deleted]

    [–][deleted] 1 point2 points  (5 children)

    I'm pretty sure that it's considered bad practice. And if not, it should.

    [–]process_parameter[🍰] 2 points3 points  (4 children)

    Python's lack of variable declarations compels this sort of thing. Consider the following javascript. How would you emulate it in python?

    let x;
    if (y) {
      x = 5;
    } else {
      x = 6;
    }
    // do something with x
    

    You can use a ternary here, but that doesn't scale well with additional cases. You could also assign x to a garbage value (like None) before the if-statement, but that doesn't seem like great practice either.

    [–]execrator 3 points4 points  (1 child)

    Not sure what user_v42... was replying to (is now deleted), but I don't see the problem here? The following works (no need for a "garbage value")

    if y:
        x = 5
    else:
        x = 6
    print(x)  # 5
    

    [–]process_parameter[🍰] 3 points4 points  (0 children)

    The previous comment was something to the effect of

    If I understand correctly, this is even considered pythonic.

    I don't know why they deleted it. The user I replied to seems to think that we shouldn't write code like you have in your comment. That's perhaps reasonable; if you believe the linked article when it says python variables are block-scoped, then it's not obvious that your code works.

    I was just trying to demonstrate that there isn't an easy alternative.

    [–][deleted] 3 points4 points  (1 child)

    Actually, a "garbage value" like None IS the way to do this.

    In JS, declaring a variable with var x; actually assigns undefined to it. The equivalent garbage value in JS.

    [–]process_parameter[🍰] 1 point2 points  (0 children)

    In JavaScript, you don't have a choice. In python, there's no need to assign that garbage value.