Live data from Hacker News

Python idioms I wish I'd learned earlier

prooffreaderplus.blogspot.com

101–110 of 174 posts

Re: Python idioms I wish I'd learned earlier

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

Common Lisp (and other dialects): ( Also: (lcm a b c d ...) ;; lowest common multiple (+) -> 0 (+ a) -> a (+ a b) -> a + b (+ a b c) -> (a + b) + c (*) -> 1 (* a) -> a (* a b) -> a * b (* a b c) -> (a * b) * c Is it just syntactic sugar? ( (and ( isn't the same as ( By the way, this could be turned into a short-circuiting operator: more semantic variation. Suppose < is allowed to control evaluation. Then an expressio…

I love clojure for providing

   (
and for making = actually useful (works on nested structures properly).

"Is this sorted", and "are these equal" are intuitive and useful concepts in programming and you shouldn't need to reimplement them each time you need them.

Re: Python idioms I wish I'd learned earlier

#102
post #76

Some comments: 1. Am I the only one that really loves that `print` is a statement and not a function? Call me lazy, but I don't mind not having to type additional parentheses. 5. Dict comprehensions can be dangerous, as keys that appear twice will be silently overridden: elements = [('a', 1), ('b', 2), ('a', 3)] {key: value for key, value in elements} == {'a': 3, 'b': 2} # same happens with the dict() constructor dic…

On the subject of "call me lazy", I really like the % syntax for string interpolation. I'd like perl-style interpolation even more. "".format() is going in completely the wrong direction for me. (I don't think % is being removed, but I think it's discouraged.)

> lambda (x, y): x + y

This syntax is removed in python 3: http://legacy.python.org/dev/peps/pep-3113/

Re: Python idioms I wish I'd learned earlier

#103
post #61

Earlier quoted context omitted.

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.

I think the comparison is more readable as (here with the >>> of the python shell):

    >>> 0 
as opposed to

    >>> 1 > x > 0
Following the number line and placing x there is nicer IMHO. Other than that, very nice trick.

Re: Python idioms I wish I'd learned earlier

#104

I came across this when I was first learning Python and it has always impressed me: from random import shuffle deck = ['%s of %s' % (number, suit) for number in '2 3 4 5 6 7 8 9 10 Jack Queen King Ace'.split(' ') for suit in 'Hearts Clubs Diamonds Spades'.split(' ')] shuffle(deck)

I never liked how people in Python use stringWithSpaces.split instead of a list. Just feels wrong somehow.

But I've seen it many times so it's probably pythonic

Re: Python idioms I wish I'd learned earlier

#105

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…

Another good/great source of Python tricks/idioms is Raymond Hettinger's "Idiomatic Python". The slides/videos are really great. I highly recommend them.

https://speakerdeck.com/pyconslides/transforming-code-into-b...

Re: Python idioms I wish I'd learned earlier

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

It's not simply syntax sugar either.

    def sideEffects():
        print "Called."
        return 5

    if 0 

Re: Python idioms I wish I'd learned earlier

#107
post #102
post #76

Some comments: 1. Am I the only one that really loves that `print` is a statement and not a function? Call me lazy, but I don't mind not having to type additional parentheses. 5. Dict comprehensions can be dangerous, as keys that appear twice will be silently overridden: elements = [('a', 1), ('b', 2), ('a', 3)] {key: value for key, value in elements} == {'a': 3, 'b': 2} # same happens with the dict() constructor dic…

On the subject of "call me lazy", I really like the % syntax for string interpolation. I'd like perl-style interpolation even more. "".format() is going in completely the wrong direction for me. (I don't think % is being removed, but I think it's discouraged.) > lambda (x, y): x + y This syntax is removed in python 3: http://legacy.python.org/dev/peps/pep-3113/

I'm still not sure why that was deprecated. It's much cleaner. I still use it… :/

Re: Python idioms I wish I'd learned earlier

#108
post #59

Earlier quoted context omitted.

I've done this before, I think of it as a more powerful form of a switch statement. I'd love to hear why you think it's not ideal.

" I'd love to hear why you think it's not ideal. " I'm not the poster you posed that question to. But for me, the one big drawback of using that idiom is that the function signatures have to be identical. So you either have to resort to args/kwargs, or you have an additional intermediary method between the actual "guts" of what you're calling, and the "switch" statement. Or you live with the fact that you're passing…

Good point, and in that case, I would say this idiom is not so great really. For functions with the same signature, it's a fine solution I think.

Re: Python idioms I wish I'd learned earlier

#110

Is there any such collection of advanced Python patterns, aimed at Python programmers with more than 2-3 years of experience?

I'd love other answers to the same question. Here are a few I've come across in the past:

http://www.rafekettler.com/magicmethods.html

http://sahandsaba.com/thirty-python-language-features-and-tr...

http://www.siafoo.net/article/52

Post reply on HN