Live data from Hacker News

Python idioms I wish I'd learned earlier

prooffreaderplus.blogspot.com

61–70 of 174 posts

Re: Python idioms I wish I'd learned earlier

#61

"Because I was so used to statically typed languages (where this idiom would be ambiguous), it never occurred to me to put two operators in the same expression. In many languages, 4 > 3 > 2 would return as False, because (4 > 3) would be evaluated as a boolean, and then True > 2 would be evaluated as False." The second half of this is correct, but it has nothing to do with whether the language is statically or dynami…

It's not just a tweak to the parser, and it does have to do with the type system, but you're right that it's not about static typing.

The issue is that there are languages (like C) where typing is static but weak, so e.g. booleans are also integers and can have integer operations like '>' applied to them. In other words, the problem is that in C True == 1 and 1 > 2 is a valid expression. In Python, which has strong(er) types, this expression can have an unambiguous meaning if you want to add the feature to your parser.

Re: Python idioms I wish I'd learned earlier

#62
I'm a fan of Python's conditional expressions.

    foo = bar if qux is None else baz
They're particularly interesting when combined with comprehensions.

    ['a' if i % 2 == 0 else 'b' for i in range(10)]
Though this particular example can be expressed much more concisely.

    ['a', 'b'] * 5

Re: Python idioms I wish I'd learned earlier

#63
post #55
post #13

Earlier quoted context omitted.

That's cute, but the result of a bad design decision. Python overloads "+" as concatenate for strings. This also applies to lists. So [1,2,3] + [4,5,6] yields [1,2,3,4,5,6] This is cute, but not what you want for numerical work. Then, viewing multiplication as repeated addition, Python gives us [1,2,3]*4 yields [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3] This is rarely what was wanted. Then there's numpy, which has its own…

I really like haskell's "++" for list concatenation. Makes a lot of sense.

Although the `++` is associated with increment from anyone coming to python from the C languages.

Its tricky; if you want to do vectors, use numpy.

Re: Python idioms I wish I'd learned earlier

#64

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 OS module interacts directly with the OS rather than abstracts it, so a lot of the functions in it have the "may not be available on all platforms" apology.

Subprocess uses OS under the hood but offers an abstraction that mostly works on all platforms, e.g. the way that "communicate" is implemented on Windows differs considerably from how its implemented on Unix.

Re: Python idioms I wish I'd learned earlier

#65
post #61

"Because I was so used to statically typed languages (where this idiom would be ambiguous), it never occurred to me to put two operators in the same expression. In many languages, 4 > 3 > 2 would return as False, because (4 > 3) would be evaluated as a boolean, and then True > 2 would be evaluated as False." The second half of this is correct, but it has nothing to do with whether the language is statically or dynami…

It's not just a tweak to the parser, and it does have to do with the type system, but you're right that it's not about static typing. The issue is that there are languages (like C) where typing is static but weak, so e.g. booleans are also integers and can have integer operations like '>' applied to them. In other words, the problem is that in C True == 1 and 1 > 2 is a valid expression. In Python, which has strong(e…

You can implement it entirely in the parser if you can avoid name capture - it may or may not be implemented entirely as a tweak to the parser in practice, but it's fundamentally a syntactic thing.

Your discussion of types here is all wrong - it's true that C treats booleans as if they were integers, but Python does, too:

    >>> (3 > 4) >> 3 > 4 >> 3 > (4 
It has nothing to do with types.

Re: Python idioms I wish I'd learned earlier

#66
post #12
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?

Perl6 has it too > perl6 > 3

3 What does 5 > 4 > 3 give?

Re: Python idioms I wish I'd learned earlier

#67
post #22

This is something I do instead of writing a long if-else: opt = {0: do_a, 1: do_b, 3: do_b, 4: do_c} opt[option]()

It's called a jump table or vtable.

It's one of the examples in Forth. Plan 9 uses that technique in C a lot too.

This example is ramfs which creates an in memory file system (that you can mount in Unix btw, in 166 LoC)

http://swtch.com/usr/local/plan9/src/lib9p/ramfs.c

fsopen, fsread, fswrite, fscreate are C functions declared in the same source file :

    Srv fs = {
	.open=	fsopen,
	.read=	fsread,
	.write=	fswrite,
	.create=	fscreate,
    };

fs is then passed to a library which calls them as needed.

Re: Python idioms I wish I'd learned earlier

#68
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?

SQL has “x BETWEEN y AND z” as a special case which does “y >= x >= z”, which in practice is quite often what you actually want to use this feature for.

Re: Python idioms I wish I'd learned earlier

#69
"Missing from this list are some idioms such as list comprehensions and lambda functions, which are very Pythonesque and very efficient and very cool, but also very difficult to miss because they're mentioned on StackOverflow every other answer!"

Can anyone link to good explanations of list comprehensions and lambda functions?

Re: Python idioms I wish I'd learned earlier

#70

Wow - that's really, really great list. In particular, #7 is something that I didn't even know existed, and I've been hacking around for 2+ years. Instead of: mdict={'gordon':10,'tim':20} >>> print mdict.get('gordon',0) 10 >>> print mdict.get('tim',0) 20 >>> print mdict.get('george',0) 0 I've always done the much more verbose: class defaultdict(dict): def __init__(self, default=None): dict.__init__(self) self.default…

Read the manuals! ;)

There's a lot of hidden gems.

Your idea is nice in a syntactic sugar way, also, the default being a part of the dictionary rather than the get function makes it copyable.

I'll give you another gem that could be interesting: else clause in for loops

Post reply on HN