Live data from Hacker News

Python Idioms [pdf]

safehammad.com

61–70 of 128 posts

Re: Python Idioms [pdf]

#61

>pets = ['Dog', 'Cat', 'Hamster'] >for pet in pets: > print('A', pet, 'can be very cute!') This may be nit picking but I prefer output like this: print 'A %s can be very cute!' %(pet)

Possibly because you haven't moved to Python 3?

Re: Python Idioms [pdf]

#62
This is a great, if somewhat basic list. My $0.02: Python is a tool for thinking clearly. That you can run your "thoughts" as written is a very nice bonus, of course.

There are some really interesting things that Python allows:

    >>> d = {}
    >>> d[23], d[14], d['hmm'] = 'abc'
    >>> d
    {'hmm': 'c', 14: 'b', 23: 'a'}

Re: Python Idioms [pdf]

#63

Interesting philosophical points. To me personally, testing for 'truthy' and 'falsy' values, or relying on exceptions rather than checking values in advance, feels like sloppy and imprecise programming. A string being empty or not, or an array having items or not, or a boolean being true or false, are all qualitatively totally different things to me -- and just because Python can treat them the same, doesn't mean a p…

but what if owners is something that looks like a dict but is not? same for name.

Re: Python Idioms [pdf]

#64
post #62

This is a great, if somewhat basic list. My $0.02: Python is a tool for thinking clearly. That you can run your "thoughts" as written is a very nice bonus, of course. There are some really interesting things that Python allows: >>> d = {} >>> d[23], d[14], d['hmm'] = 'abc' >>> d {'hmm': 'c', 14: 'b', 23: 'a'}

I couldn't resist. Moar funky-cool Python:

    >>> from string import ascii_letters
    >>> ors = ['|'] * (len(ascii_letters) * 2 - 1)
    >>> ors[::2] = ascii_letters
    >>> ''.join(ors)
    'a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z'
(Obviously, in this example '|'.join(ascii_letters) would suffice, but if the objects weren't strings...)

Re: Python Idioms [pdf]

#65
Although many of them boil down to preferences and philosophical points of view, I find these kinds of idioms useful. Whenever I write code in a new language, I want to "write as a native" so that I can maximize the effect that the language has on how I think about programming.

For Python in particular, Jeff Knupp's "Writing Idiomatic Python"[1] (not free, but not expensive, either) goes into detail on a lot of the concepts in the OP's slides. (I'm not affiliated with Jeff in any way, just a satisfied customer.)

[1] http://www.jeffknupp.com/writing-idiomatic-python-ebook

Re: Python Idioms [pdf]

#66

As an implementor of Hy (a homoiconic lisp frontend to Python) I've found certain Python idioms to be rather infuriating of late. In particular: >>> 0 == False True Which makes the idiom of testing truthiness quite annoying in parsing code such as: def is_digit_char(s): """ Return a parsed integer from 's'.""" try: return int(s) except (ValueError, TypeError): return None Which is harmless enough except that as a pre…

This reminds me, somewhat tangentially, of a bug I ran into once with Tcl (yes, Tcl) where a function returned an integer in the form "08" and Tcl had a convention that any integer with a 0 prepended would be treated as octal in any arithmetic expressions. Naturally, 8 is not a valid octal digit, so this broke everything when it happened.

Ultimately it was my fault for not being better acquainted with the language, but that one still caught me by surprise.

Re: Python Idioms [pdf]

#67

Earlier quoted context omitted.

It's a trivial example and I wouldn't focus on it too much. It's not that peculiar -- instead of parsing the same character twice you simply return the value that you parsed or None. My inspiration was from the CLHS predicate function, DIGIT-CHAR-P [0]. The real point I was making is that Python has warts that make writing idiomatic code impractical in some situations. I suggest that practicality take precedence over…

> In other words, anything that isn't False is True. :D Except for `nil` (lisps, ruby), and possibly a host of other things depending on the language (empty strings in javascript).

Scheme is the only PL I know that has an explicit #f value.

CL, for all intents and purposes, treats nil as False... but some find the conflation of nil and the empty list runs into the same issue when operating on s-exprs.

    CL-USER> (if '() 1 0)
    0
vs

    scheme> (if '() 1 0)
    1

Re: Python Idioms [pdf]

#68
post #56

Interesting philosophical points. To me personally, testing for 'truthy' and 'falsy' values, or relying on exceptions rather than checking values in advance, feels like sloppy and imprecise programming. A string being empty or not, or an array having items or not, or a boolean being true or false, are all qualitatively totally different things to me -- and just because Python can treat them the same, doesn't mean a p…

I think the point of the article, and of idioms in general, is that they make code "better" (e.g. some combination of clearer, shorter, cleaner, etc.) for the community of coders who are familiar with the idioms. The obvious downside of idioms is that a programmer needs to learn the idioms to reap these advantages. So I suppose whether you should encourage idioms in your code base would depend on who will be working…

Nonetheless, you should reconsider from time whether those idioms are actually helpful for those in the community. I personally dislike 'if name and pets and owners:' because it removes the information of what is happening at this line of code and I have to look up what type name, pets and owners actually are.

Re: Python Idioms [pdf]

#69

Interesting philosophical points. To me personally, testing for 'truthy' and 'falsy' values, or relying on exceptions rather than checking values in advance, feels like sloppy and imprecise programming. A string being empty or not, or an array having items or not, or a boolean being true or false, are all qualitatively totally different things to me -- and just because Python can treat them the same, doesn't mean a p…

No. What if 'owners' is a collections.defaultdict, or some other dict-like type?

Re: Python Idioms [pdf]

#70
post #64
post #62

This is a great, if somewhat basic list. My $0.02: Python is a tool for thinking clearly. That you can run your "thoughts" as written is a very nice bonus, of course. There are some really interesting things that Python allows: >>> d = {} >>> d[23], d[14], d['hmm'] = 'abc' >>> d {'hmm': 'c', 14: 'b', 23: 'a'}

I couldn't resist. Moar funky-cool Python: >>> from string import ascii_letters >>> ors = ['|'] * (len(ascii_letters) * 2 - 1) >>> ors[::2] = ascii_letters >>> ''.join(ors) 'a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z' (Obviously, in this example '|'.join(ascii_letters) would suffice, but if the objects weren't strings...)

Not gonna lie... your snippet made me say "WTF?" Why not just do:

  from string import ascii_letters
  '|'.join( ascii_letters )
(I also like list slicing... but only when necessary.)
Post reply on HN