Live data from Hacker News

Python idioms I wish I'd learned earlier

prooffreaderplus.blogspot.com

131–140 of 174 posts

Re: Python idioms I wish I'd learned earlier

#131
post #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

It's like old Perl idiom where Python's 'ab cd ef'.split(), would be written as qw(ab cd ef), which probably looks nicer --'qw' stands for 'quote words', I think.

Re: Python idioms I wish I'd learned earlier

#132

I wish there was an interval set in Python's builtins. I also wish that ranges were an actual proper set implementation - so you could, for example, take intersection and union of ranges. And I wish that Python had an explicit concatenation operator.

You mean like the built in `set` object? https://docs.python.org/2/library/stdtypes.html#set

I think he or she meant a specialized set data structure that stores sets of numbers which can be written as finite unions of interval. Typically besides set operations you'd also want (1) that only endpoints of the intervals are stored, so that the structure is compactly represented in memory, (2) to be able to recover the canonical representation of the set as a sorted union of disjoint intervals.

Re: Python idioms I wish I'd learned earlier

#133

I wish there was an interval set in Python's builtins. I also wish that ranges were an actual proper set implementation - so you could, for example, take intersection and union of ranges. And I wish that Python had an explicit concatenation operator.

You mean like the built in `set` object? https://docs.python.org/2/library/stdtypes.html#set

Set doesn't work for this.

You need to store all possible numbers between the lower and upper bound, which isn't exactly workable for (for example) floats.

Re: Python idioms I wish I'd learned earlier

#134

Earlier quoted context omitted.

You mean like the built in `set` object? https://docs.python.org/2/library/stdtypes.html#set

I think he or she meant a specialized set data structure that stores sets of numbers which can be written as finite unions of interval. Typically besides set operations you'd also want (1) that only endpoints of the intervals are stored, so that the structure is compactly represented in memory, (2) to be able to recover the canonical representation of the set as a sorted union of disjoint intervals.

This is exactly what I meant, thank you.

Re: Python idioms I wish I'd learned earlier

#135
post #18

Earlier quoted context omitted.

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…

But can any lisp dialect do: a = c ?

Yes, for instance in Common Lisp we can make ourselves a rel macro, such that

   (rel a = c)
evaluates a, b, c once, left to right, and then performs the comparisons between the successive evaluated terms.

  $ cat rel.lisp 
  (defmacro rel (&rest args)
    (loop for expr in args by #'cddr
          for g = (gensym)
          collect g into gens
          collect `(,g ,expr) into lets
          finally (return `(let ,lets
                             (and
                               ,(loop for (left op right) on args by #'cddr
                                      for (lgen rgen) on gens
                                      while rgen
                                      collect `(,op ,lgen ,rgen)))))))

  $ clisp -q -i rel.lisp 
  ;; Loading file rel.lisp ...
  ;; Loaded file rel.lisp
  [1]> (macroexpand '(rel))
  (LET NIL (AND NIL)) ;
  T
  [2]> (macroexpand '(rel x))
  (LET ((#:G3219 X)) (AND NIL)) ;
  T
  [3]> (macroexpand '(rel x  (macroexpand '(rel x = z))
  (LET ((#:G3222 X) (#:G3223 Y) (#:G3224 Z))
   (AND ((= #:G3223 #:G3224)))) ;
  T
  [5]> (macroexpand '(rel x = z = #:G3226 #:G3227) (
Could use some error checking, obviously, to make it a production-quality macro.

Re: Python idioms I wish I'd learned earlier

#136
post #24

Earlier quoted context omitted.

I personally don't like this style of using multiple strings. Makes radical changes of the text cumbersome. I think in most cases it's better to use triple quotes. And if the content of these variables isn't exclusively shown in the shell, you should use translation files anyway.

$ cat triple.py def foo(): print """this is a triple quoted string this is a continuation of a triple quoted string""" if __name__ == '__main__': foo() $ python triple.py this is a triple quoted string this is a continuation of a triple quoted string This is really warty. In bash you can mostly get around this with e.g. $ function usage() { cat

I don't have an opinion positive or negative on it, but since many other design decisions have already been mentioned, here is Haskell's design decision for multi-line string literals. It allows "tidy indenting", but like the first design decision, interacts badly with "reflowing / reformatting / filling".

http://book.realworldhaskell.org/read/characters-strings-and...

Re: Python idioms I wish I'd learned earlier

#137
post #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

As DaFranker points out, it's just easier to type than

    ('Hearts', 'Diamonds', 'Spades', 'Clubs')
and has less opportunity for typos and syntax errors. If I was concerned about performance I would replace it with a tuple, but it was Good Enough for a quick example.

Re: Python idioms I wish I'd learned earlier

#138
If you were underwhelmed by this blog post have a look at:

Transforming code into Beautiful, Idiomatic Python by Raymond Hettinger at PyCon 2013

https://speakerdeck.com/pyconslides/transforming-code-into-b... and https://www.youtube.com/watch?v=OSGv2VnC0go&noredirect=1

Topics include: 'looping' with iterators to avoid creating new lists, dictionaries, named tuples and more

Re: Python idioms I wish I'd learned earlier

#139
post #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

also in the std library, https://docs.python.org/3/library/collections.html#collectio... field_names can take a single space separated string

Re: Python idioms I wish I'd learned earlier

#140
post #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

I love this idiom. I also use it in Javascript.
Post reply on HN