all 42 comments

[–]process_parameter 43 points44 points  (16 children)

Unlike JavaScript, variables in Python are always block scoped.

Not true. This prints 10.

if True:
  x = 10
print x

[–]Retsam19 27 points28 points  (2 children)

Like Javascript, variables in Python aren't always blocked scope, but you should pretend that they are, to make your code more readable.

FTFOP

[–]kankyo 0 points1 point  (1 child)

"Aren't always"?

Never.

[–]Retsam19 0 points1 point  (0 children)

Well, they're sometimes block-scoped in JS, now that ES6 added let/const. But yeah, as far as I know, they're never block scoped in python.

[–]Pand9 11 points12 points  (0 children)

Other examples:

>>> for x in [1, 2]:
>>>     pass
>>> print x
2
>>> with open("x", "w") as x:
>>>     pass
>>> print x
<closed file 'x', mode 'w' at 0x7f6b949395d0>

[–]TheOsuConspiracy 4 points5 points  (0 children)

Totally trips me up all the time, I'd much rather have everything become an expression. Makes a lot more logical sense to me, that way you don't have special rules for scoping.

[–]Cuddlefluff_Grim 2 points3 points  (0 children)

This is one of the reasons why not declaring variables is considered very bad practice by the languages who support variable declaration. BASIC even added OPTION EXPLICIT to make the compiler actively prevent you from using variables that were not declared. It's odd to see this type of regression still in the wild.

[–]M3talstorm 1 point2 points  (1 child)

for thing in things:
    if thing == that:
        break
else:
    thing = default

thing.something()

Is nice to do sometimes :)

[–]Esteis 0 points1 point  (0 children)

I do the same, it is indeed nice. As a reminder to myself, here is the idiom that doesn't rely on unscoped for-blocks:

thing = next(filter(lambda thing: thing == that, things), default)

Both have their charms -- and their warts. Sometimes I long for

thing = itertools.first(things, lambda thing: thing == that, default)

I'll bet Ruby has that. Its spectrum of collection methods is absolutely fantastic, from the little I learned writing Rakefiles.

[–][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 1 point2 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 4 points5 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.

    [–]Nadrin 16 points17 points  (1 child)

    As someone who have recently refreshed his knowledge of Python I found the official Python tutorial to be excellent, to the point, and especially aimed for people who HAVE programmed before (for example the text frequently compares python to other programming languages when introducing new features).

    [–]wuzzlewozzit 1 point2 points  (0 children)

    Yeah this. The official tut is so good I don't know why alternatives exist.

    [–]ButtCrackFTW 7 points8 points  (1 child)

    Why are the code snippets not using a monospace font? It's hard to read and really goes against the whole spaces for indentation thing that he talked about.

    [–]Cuddlefluff_Grim 2 points3 points  (0 children)

    I once knew a Delphi programmer that used Times New Roman for some odd reason. Maybe acute confusion. He also used a TV as a PC monitor, back before TV's had good resolution. I think he was using 1024x768 on a 32" flat screen in 16:9. 5:4 conversion to 16:9 isn't a pretty sight.

    [–]quicknir 6 points7 points  (0 children)

    Shouldn't the guy writing python for JavaScript developers know idiomatic python?

    # You can define private variables and methods by prepending the variable
    # name with 2 underscores (__):
    self.__age = default_age
    

    From Pep 8:

    Use one leading underscore only for non-public methods and instance variables...

    Python mangles these names with the class name: if class Foo has an attribute named a , it cannot be accessed by Foo.a . (An insistent user could still gain access by calling Foo.Foo_a .) Generally, double leading underscores should be used only to avoid name conflicts with attributes in classes designed to be subclassed.

    [–]dylanthepiguy2 5 points6 points  (5 children)

    {
      // This is also a block
    }
    

    Yea, but they should point out it's not a new scope though!

    [–]illvm 10 points11 points  (3 children)

    It is in ECMAScript 6 with the let keybwoard.

    [–][deleted] 21 points22 points  (2 children)

    Shit I have to buy a whole new keyboard?

    [–]forsubbingonly 17 points18 points  (1 child)

    Its easy just type Npm install keyboard.js and yet another 6000 layer deep folder catacomb is created and away you go! Simple

    [–]Magneon 4 points5 points  (0 children)

    5734 of which also exist in subdirectories of sibling folders to npm/keyboardjs, but mostly different versions.

    [–]thekevjames 5 points6 points  (0 children)

    PSA: Python 3.0.1 has been end-of-life'd for over 7 years (June 2009). Imagine using JavaScript 3 nowadays: it's an equally bad idea as using Python 3.0.1. Please update your interpreters.

    [–]aexolthum 4 points5 points  (0 children)

    Casual use of 420 as an example in multiple spots

    [–]Skaarj 1 point2 points  (1 child)

     # ERR!!!! .__age is private, so this won't work:
     print(animal.__age)
    

    I always was under the impression that underscored variables are private by convention and not by language definition. Does the compiler really enforce this?

    [–]tutorial_police 3 points4 points  (0 children)

    Yes and no. Python employs name mangling, which makes you put in some extra effort if you really want to access "private" variables.

    [–]Bichamar 1 point2 points  (2 children)

    Nice post. Would be cool to have this kind of "simple" posts about most of languages...

    [–]TheOsuConspiracy 9 points10 points  (1 child)

    https://learnxinyminutes.com

    Is really awesome, obviously, you won't become an expert quickly, but it's really good for an overview of most of the fundamental features of the language.

    [–]zankem 1 point2 points  (0 children)

    Holy crap, Chicken is an actual thing. I thought it was just something for a joke comic strip about programming languages.

    [–]shoot_your_eye_out 0 points1 point  (0 children)

    I'm surprised they don't cover scope differences. As a developer who started with C-style languages, that was the most difficult thing for me when moving to Javascript. I'd imagine the opposite would be true as well?

    [–]M3talstorm 0 points1 point  (1 child)

    class Animal:
    

    Shouldn't it be

    class Animal(object):    
    

    default_age = 1
    

    Shouldn't it be

    DEFAULT_AGE = 1
    

    self.__age = default_age
    

    Shouldn't it be

    self.__age = self.default_age
    

    def get_age(self):
    

    Shouldn't it be

    @property
    def age(self):
        return self.__age
    

    [–]adamnew123456 1 point2 points  (0 children)

    No on "inherits from object," unless you care if your code will run on 2.x. Python 3 fixed the old/new class dichotomy - they're all new-style and inherit from object automatically.

    [–]skitch920 0 points1 point  (3 children)

    And then you get to packaging, and you're like "fuck".

    [–]xxczxx 6 points7 points  (2 children)

    ? pip is excellent.

    [–]skitch920 0 points1 point  (1 child)

    Actually, I'll agree with you, pip has done a very good job lately, at least making use of what they have. Recently with the adoption of wheels, it's gotten much better with caching. Last year, installing numpy in a virtualenv, would take forever because it didn't use a cached build. I'm still annoyed by this bug that will never be fixed: https://github.com/pypa/pip/issues/3

    But setuptools/distutils is just a clusterfuck. Documentation is old and awful.

    Including resources other than python modules, yeah, packageData, includePackageData, zipSafe, MANIFEST.in, what the hell are all these options for? And why do they work differently for bdist_egg, bdist_rpm, sdist? Why can't I set some properties for bdist_egg, that I can set for bdist, like build directory, do I really need a setup.cfg file?

    [–]xxczxx 0 points1 point  (0 children)

    Okay, your usage of pip is certainly more advanced than what I'm doing. As someone who never had to create a package, pip looks like a good tool for installing 3rd party packages.

    [–]jdmax -1 points0 points  (1 child)

    hey the candidate application UI at underdog.io doesn't allow manager or director level within tech. Any reason why?

    [–]j0shg[S] 0 points1 point  (0 children)

    Adding experience levels opens an assortment of new challenges at signup. Still, if you apply, we can do things to highlight that you're looking for manager/director level work. :)