Live data from Hacker News

Python Idioms [pdf]

safehammad.com

11–20 of 128 posts

Re: Python Idioms [pdf]

#11
As a huge Python fan, I'm ashamed to admit but I don't get the

    while True:
        break
What's the problem? I supose the use case is

    while True:
        # do stuff
        if some_condition:
            break
What is the alternative? 'while some_condition'? That means we must have the 'some_condition' variable outside of the loop. And if we have multiple exit points it may become a mess.

Re: Python Idioms [pdf]

#12

> 9. Create dict from keys and values using zip In 2.7+, I'd recommend a dictionary comprehension instead.

In this case,

    {k: v for k, v in zip(keys, values)}
edit:

As I mention below, this becomes useful when you want to do e.g.

    {f(k): g(v) for k, v in zip(keys, values)}

Re: Python Idioms [pdf]

#13
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 programmer should take advantage of that fact. Sometimes it's possible to over-simplify things in a way that obfuscates instead of clarifying.

When I read:

    if name and pets and owners
I have no intuitive idea of what that means, of what's going on in the program. When I read

    if name != '' and len(pets) > 0 and owners != {}
I understand it exactly.

But by this point, I've come to understand that, for a lot of people, it seems to be the opposite. It seems to be more of a philosophical difference, not right/wrong.

Re: Python Idioms [pdf]

#14
post #12

> 9. Create dict from keys and values using zip In 2.7+, I'd recommend a dictionary comprehension instead.

In this case, {k: v for k, v in zip(keys, values)} edit: As I mention below, this becomes useful when you want to do e.g. {f(k): g(v) for k, v in zip(keys, values)}

I'd disagree, as

  dict(zip(keys, value))
is more concise, doesn't introduce extra variables, and doesn't repeat itself, and explicitly names a dict rather than using a symbol.

Re: Python Idioms [pdf]

#15
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 predicate it sucks because parsing "0" will return False in a context where I'd rather know whether I parsed an integer or not... which leads to non-idiomatic code.

This is mainly because True/False are essentially aliases for 1/0 and as such won't identify so:

    >>> 0 is False
    False
    >>> 0 is 0
    True
So it's important to remember another Tim Peters-ism: Although practicality beats purity. As read in the Zen of Python it seems he's referring to special cases which this might be.

As a shameless aside, you should see what we're working on in Hy. There will likely come a point where we'll be able to do kibit-style suggestions of idiomatic transformations to your Python code.

Update: I ran into this while trying to write token parsers for a parser-combinator lib in Hy.

Re: Python Idioms [pdf]

#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]

Re: Python Idioms [pdf]

#17
post #5

I don't understand the truth table on slide 9 for " - vs None " and "__nonzero__ (2.x) " __bool__ (3.x) vs __nonzero__ (2.x) " __bool__ (3.x) "

I'm pretty sure the "-" vs "None" meant that there wasn't a truthy alternative to None. More accurate would have been "N/A" vs "None". Not clear on the __nonzero__/__bool__ stuff...

Re: Python Idioms [pdf]

#18
For point 10:

'_' is often aliased as gettext to ease translation of string:

    from django.utils.translation import ugettext as _

    translated_str = _('Something to translate')
so using it will overwrite the alias. Instead, you can use '__' (double underscore) as ncoghlan suggests below his answer [1]. or you can use the 'unused_' prefix as Google Python Style Guide suggests [2] or you can change your code, so you don't need to use '_' as Alex Martelli suggests in his answer [3].

[1]: http://stackoverflow.com/a/5893946/720077

[2]: http://google-styleguide.googlecode.com/svn/trunk/pyguide.ht...

[3]: http://stackoverflow.com/a/1739541/720077

Re: Python Idioms [pdf]

#19

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 part of the reasoning behind the truthy / falsy mechanic is that it's more robust. If, for whatever reason, we did:

  name = None
instead of

  name = ''
Then the second conditional would fail, whereas the first would still be fine.

Re: Python Idioms [pdf]

#20
post #5

I don't understand the truth table on slide 9 for " - vs None " and "__nonzero__ (2.x) " __bool__ (3.x) vs __nonzero__ (2.x) " __bool__ (3.x) "

He's referring to the special methods available to classes that allow implementation of the truth value of an object. In version 2.x of Python, this method is __nonzero__[1] and in version 3.x it's called __bool__[2]

[1] http://docs.python.org/2/reference/datamodel.html#object.__n...

[2] http://docs.python.org/3/reference/datamodel.html#object.__b...

Post reply on HN