1. 13
  1. 2

    The post contains some gems like variable unpacking, the “bunch idiom” and not recommending functional idioms without a good reason (it is tough to visually parse non-trivial Python code that abuses map, filter and reduce). Still, there is a detail I disagree with:

    Using is None, is True or is False isn’t just about convention or improved readability though. It also improves performance, especially if you would use x is None instead of x == None inside loop.

    Yes, always check for None using x is None. However, I think that using is True and is False are just noise: if an expression is true or false, it already evaluates to true or false. Furthermore, Python has a set of values that are implicitly true or implicitly false, which is super useful to make terse condition checks. For example, assuming elements is a list; these two conditions are the same:

    if len(elements) == 0 is True:
        # do something
    if not elements:
        # do something

    I consider the latter to be much more pythonic and easy to read. However, this is just a bit of nitpicking - great work, and thanks for sharing!

    1. 2

      This is a great piece, thanks for writing & sharing!

      Python is one of those languages that I write infrequently enough that I don’t have an “innate” sense of what it means to write idiomatic Python code, whereas I do have that sense for other languages. That usually means for me that my Python scripts end up looking like the language I’ve been using most recently, and I’ve come across Python files I’ve written that feel like I’m reading Node, Swift, or even Rust in a strange dialect.

      One way to get better at writing idiomatic code would be to read articles like this one, compile all the individual tips, and reference those tips when writing new Python. It seems to me like a more sticky way to get better at writing idiomatic Python code would be to read idiomatic Python code, but whenever I sit myself down to read code I don’t have any stake in, I feel like it’s a waste of my time.

      Do other people incorporate “reading code” into their process? How?

      1. 2

        For me the “reading code” comes from the need to use big libraries extensively and understanding their inner workings. For example, I often have to dig into libs like requests or flask. So, I think you start reading more code as you use the language more.

      2. 1

        This doesn’t load?

        1. 1

          It loads for me, if you have trouble accessing it, you can also view it here.