Live data from Hacker News

Python idioms I wish I'd learned earlier

prooffreaderplus.blogspot.com

1–10 of 174 posts

Re: Python idioms I wish I'd learned earlier

#2
I'm not much of a Python guy, but that chained comparison operator is sweet!

Sure, it's just syntax sugar, but it saves a lot of keystrokes, especially if the variable name is long.

Is Python the only language with this feature?

Re: Python idioms I wish I'd learned earlier

#4
I think the example in #4 misses the point of using a Counter. He could have done the very same for-loop business if mycounter was a defaultdict(int).

The nice thing about a Counter is that it will take a collection of things and... count them:

    >>> from random import randrange
    >>> from collections import Counter
    >>> mycounter = Counter(randrange(10) for _ in range(100))
    >>> mycounter
    Counter({1: 15, 5: 14, 3: 11, 4: 11, 6: 11, 7: 11, 9: 8, 8: 7, 0: 6, 2: 6})
Docs: https://docs.python.org/2/library/collections.html#counter-o...

Re: Python idioms I wish I'd learned earlier

#6
post #2

I'm not much of a Python guy, but that chained comparison operator is sweet! Sure, it's just syntax sugar, but it saves a lot of keystrokes, especially if the variable name is long. Is Python the only language with this feature?

I'm not sure if other languages have it, but I have to say that pycharm is excellent at suggesting chained comparisons to you. I didn't know this existed before I switched IDEs.

if 2 > 3 and 2 becomes

if 3 < 2 < 7

Re: Python idioms I wish I'd learned earlier

#7
post #2

I'm not much of a Python guy, but that chained comparison operator is sweet! Sure, it's just syntax sugar, but it saves a lot of keystrokes, especially if the variable name is long. Is Python the only language with this feature?

> Is Python the only language with this feature?

No. See, e.g., http://stackoverflow.com/questions/4090845/language-support-...

Re: Python idioms I wish I'd learned earlier

#8

Can someone direct me to a comparision of subprocess and os? I keep hearing subprocess is better, but have not really read any explanation as to why or when it is better. (I'm glad I'm not the only one who was thrilled to discover enumerate()!)

The subprocess module is meant to replace a number of functions in the os module. The python documentation lists a number of examples here: https://docs.python.org/2/library/subprocess.html#subprocess...

If you google 'os vs subprocess python' there are a few stackoverflow and quora threads comparing them.

Re: Python idioms I wish I'd learned earlier

#10
> There is a solution: parentheses without commas. I don't know why this works, but I'm glad it does.

It's worth mentioning that this is a somewhat controversial practice. Guido has even discussed removing C-style string literal concatenation:

http://lwn.net/Articles/551438/

You may wish to consult your project's style guide and linter settings before using it.

Post reply on HN