Live data from Hacker News

Python idioms I wish I'd learned earlier

prooffreaderplus.blogspot.com

91–100 of 174 posts

Re: Python idioms I wish I'd learned earlier

#91
post #88

Earlier quoted context omitted.

> 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. If you think the parentheses are bad, why wouldn't you prefer a language like Ruby where you can omit them generally? Leaving them out for just one special construct seems so insufficient as a cure.

In general, Ruby's syntax (or rather, semantics) is ambiguous (you don't know if a statement without parentheses is calling a function or just accessing a value). I prefer unambiguous syntax. However, Python's `print` statement is (1) well-known, (2) very useful (for prototyping, debugging, in REPL), and (3) shouldn't in general be present in production code (logging should be used instead). Therefore, omitting paren…

tom, get back to work!

Re: Python idioms I wish I'd learned earlier

#92
post #89
post #85

Earlier quoted context omitted.

print-as-a-function has a few nice qualities, like the ability to pass it around as an argument to things so you can do (stupid example): map(print, range(10)) It can also take some kwargs that allow you to do things that are a bit clunky with the print statement. Which is the more intuitive of the following?: print(errmsg, file=sys.stderr) print >>sys.stderr, errmsg (I didn't even know about the latter until I found…

The first really has nothing to do with `print` being a statement - it could be parsed and passed as a function in "non-statement" positions regardless. The rest could probably be special-cased in a backwards-compatible way as well. This is currently not valid Python 2.0 syntax: print "cats", end='', file=sys.stderr

well, as a statement it's also a reserved keyword, so you can't override or mock it (AFAIK), and I suspect changing the parser to identify context and operate accordingly might be rather painful.

Honestly, I'm reasonably happy with the split; there don't seem to be many compelling reasons to shoehorn all the extra bits back into statement-print other than

a) removing a single pair of parens

b) being backwards compatible (but then the old code wouldn't be using those new features anyway, and would still have to support that nasty bitshift hack.

Re: Python idioms I wish I'd learned earlier

#93
post #25
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]()

Do you consider that to be idiomatic? I've been out of touch with the a Python community for a few years, but back then I wouldn't have considered that remotely idiomatic, and if I was on a team writing software, I would have argued that we shouldn't be writing code like that.

It's still nicer than the

   func = getattr(self, 'do_%s' % thing)
   func(args)
I've seen in some codebases :)

Re: Python idioms I wish I'd learned earlier

#94

Earlier quoted context omitted.

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

If this Pycharm really had brains it would tell you that (2>3 and 2<7) reduces to (false and true), to false, at compile time, so the code wrapped in the if is unreachable.

I'm not sure about pycharm, but i know for certain IntelliJ warns you about constant conditions like that. That said, he could have picked that example just to illustrate a point, rather than something it literally suggests.

Re: Python idioms I wish I'd learned earlier

#95
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)

Re: Python idioms I wish I'd learned earlier

#96

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

Before the conditional expression was introduced to Python I sometimes wrote things like

    foo = [baz, bar][qux is None]

Re: Python idioms I wish I'd learned earlier

#97

"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?

This seems like an easy intro to list comprehensions:

http://www.pythonforbeginners.com/basics/list-comprehensions...

Re: Python idioms I wish I'd learned earlier

#98
post #47

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 don't think it's more powerful in any way than an if-elif-elif-else which, for what it's worth, I consider the Pythonic way. Having said that, just because I consider something more Pythonic doesn't mean I prefer it. I've worked in a lot of languages over the years and still work in several in addition to Python. I really enjoy Python, but I prefer techniques that are more universal in many cases. For example, I pr…

It's strange that you would prefer `for item in items` but not `for i, item in enumerate(items)`. So in that case you'd manually do the `for i in range(len(items))...`?

I sometimes see this in code and think to myself, whoever wrote this needs to learn themselves some idiomatic python :) I don't think there's much point trying to force stuff that makes sense in one language into another language. Play to a languages strengths and all that.

I think you're right about if-elif generally being more powerful than the jump table. Though the jump table is useful in that you can define it in one place and use it in another.

Re: Python idioms I wish I'd learned earlier

#99

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

Also read other people's code :) You'll see this being used countless times in libraries / on GitHub.

Re: Python idioms I wish I'd learned earlier

#100
post #88

Earlier quoted context omitted.

In general, Ruby's syntax (or rather, semantics) is ambiguous (you don't know if a statement without parentheses is calling a function or just accessing a value). I prefer unambiguous syntax. However, Python's `print` statement is (1) well-known, (2) very useful (for prototyping, debugging, in REPL), and (3) shouldn't in general be present in production code (logging should be used instead). Therefore, omitting paren…

tom, get back to work!

It is thanksgiving, lay off Tom.
Post reply on HN