Live data from Hacker News

Python Idioms [pdf]

safehammad.com

91–100 of 128 posts

Re: Python Idioms [pdf]

#91
post #79

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…

It's a dynamic-typing thing. In some hypothetical static-strong-non-duck version of Python, if name != '' and len(pets) > 0 and owners != {} would tell you that name is a non-empty string, pets has values, and owners is a non-empty dict (except it doesn't work, as pdonis noticed). But Python allows immoral implicit conversions, so that's not what that line means! If name is a function, pets is the value '7' and owner…

Sure, if you view the code as a conversation between the reader and the compiler, but as a conversation between the reader and the writer, I would hope that those inferences (e.g. name is a non-empty string) would be reasonable.

Re: Python Idioms [pdf]

#92
post #83

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 c…

What level would you say the idioms in the book are at? I have already been programming in python for a little while, and I wouldn't want to pay for something which I already know. It would be nice if there were more sample idioms on that site so you could have a better idea of what the rest of the book was like.

Given that the author is willing to give away copies to those that can't afford the book, I'm sure he'll consider a preview/promise refund if you send him an email? (See bottom of page).

Note: Also not affiliated in any way.

[edit: given:

http://www.goodreads.com/book/show/17354838-writing-idiomati...

it doesn't look like it's of all that much value to an experienced python developer. I'd love to hear some other comments, though.]

Re: Python Idioms [pdf]

#94
post #44

Earlier quoted context omitted.

Your function is_digit_char(s) is peculiar. From the name I would expect it to return a boolean, instead it returns a number or None. To write it like that and have a problem with the falseness of 0 it means that you use it in a way to both use it as conditional expression and an integer value, e.g. digit = is_digit_char('0') if digit: # fail print(digit) else: print('not a digit') You should then check for his equal…

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…

What is a "wart" is subjective. C-like languages also have this "wart" and it's used to great effect, enabling different idioms that would be messier without it.

Re: Python Idioms [pdf]

#95
post #80

Earlier quoted context omitted.

I have personally never seen this before. I'd be wary to use it, since it breaks the "_ is a throwaway" idiom, as well as the REPL "_ is the results of the last expression" function. Aliasing it to "t" or "txl" seems like a saner way, if I'm honest.

This has been established practise in Zope, Plone et al for many years. http://developer.plone.org/i18n/internationalisation.html#ma...

It's standard Python practice since Martin von Löwis's work in support for internationalization, which he presented at the IPC6 Python conference in 1997.

Quoting from http://www.python.org/workshops/1997-10/proceedings/loewis.h... :

> Here are several ways of producing the message catalogs. This is the one suggested by the GNU gettext documentation. First, all translatable message strings in the source code must be marked. In order to disturb readability as little as possible, the wrapper function around each string should be called _ (underscore). This use of the underscore usually does not interfere with its meaning in the interactive mode. A gettextized module would then begin with

    import intl
    
    _=intl.gettext

Re: Python Idioms [pdf]

#96
post #86
post #79

Earlier quoted context omitted.

It's a dynamic-typing thing. In some hypothetical static-strong-non-duck version of Python, if name != '' and len(pets) > 0 and owners != {} would tell you that name is a non-empty string, pets has values, and owners is a non-empty dict (except it doesn't work, as pdonis noticed). But Python allows immoral implicit conversions, so that's not what that line means! If name is a function, pets is the value '7' and owner…

owners is a non-empty set. No, it doesn't tell you that. {} denotes an empty dict, not an empty set; and an empty set will return True for owners != {}, not False. As I noted in another post upthread, you would need to write len(owners) > 0 to get the correct semantics, making owners indistinguishable from pets even if they are different container types. If you really wanted to make all the types clear, you would nee…

You're right, edited.

Re: Python Idioms [pdf]

#97
post #83

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 c…

What level would you say the idioms in the book are at? I have already been programming in python for a little while, and I wouldn't want to pay for something which I already know. It would be nice if there were more sample idioms on that site so you could have a better idea of what the rest of the book was like.

It's of more use to a new Python developer than an old hand, but it does touch on some relatively unknown language features (eg for loops having an else clause). Honestly, though, it's only $10, so it's not a massive investment.

Re: Python Idioms [pdf]

#99
post #76

Earlier quoted context omitted.

I've personally run into problems when I don't do exact comparisons with True and False. For example, I've forgotten to return a value in one path of a function/method, and then tried to use the result in an if statement in the style recommended by the OP (e.g. if fcall(): do something). After being bitten several times by this, I always do explicit comparisons.

So you never use "else"? Else is the mother of inexact comparisons.

Use the else to let you know that something is going wrong, using raise or exit() or some die() function:

    if something:
        do_this()
    elif something_else:
        do_that()
    else:
        # hope we don't end up here
        raise UserWarning('We shouldn't have ended up here')

Re: Python Idioms [pdf]

#100
post #16

Thanks for this write up. I didn't know about enumerate. I never thought of swapping variables as in example 4 either. I noticed one small mistake in section 9: d[keys] = values[i] Should be: d[key] = values[i]

For a good few months I was doing

    for i in range(len(input_list)):
        v = input_list[i]
        ...do something with v and i...
enumerate is much nicer!

    for i, v in enumerate(input_list):
        ...
Post reply on HN