Live data from Hacker News

Python Idioms [pdf]

safehammad.com

41–50 of 128 posts

Re: Python Idioms [pdf]

#41
post #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…

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.

Re: Python Idioms [pdf]

#42
post #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.

Personally, because I find infinite loops to be a real PITA, I prefer to do: for _ in xrange(100000): break else: logging.error("ran into an infinite loop") unless I really do need an infinite loop for things like event handler loop, which is admittedly quite rare.

Doesn't it bother you that this code is technically completely wrong?

Re: Python Idioms [pdf]

#43
post #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...

__nonzero__/__bool__ are the methods called on objects when evaluating truthiness. So, if you're implementing custom objects, those are what you would use, and return either True or False, based on their truthiness value.

As an example, you might represent __bool__ on a database connection object to reflect whether there is a live connection, allowing you to:

    if not conn:
        conn = MySQLdb.Connect()

Re: Python Idioms [pdf]

#44

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…

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 equality to None

     digit = is_digit_char('0')
     if digit is None: # pass
         print('not a number')
      else:
         print(digit)
But I would argue that you were in search for troubles when you wrote an is_something() function that doesn't return a boolean. That is not idiomatic.

p.s. Hy is too crazy :-)

Re: Python Idioms [pdf]

#45
post #34

Earlier quoted context omitted.

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.

Checking for empty strings can be done with len(mystring)==0 for this reason. In many other languages this method is standard and recommended practice. Relying on implicit conversions is just sloppy. What if that variable was never supposed to be None in the first place. Better with an exception than continuing with corrupt data. Remember another python motto: Explicit is better than implicit.

If you need to differentiate between the empty string and None, you can, but in most situations the difference isn't important. E.g., would you ever actually display the values differently? Exaggerated explicitness can be misleading. E.g., if a year from now someone is making some changes, should they really be distracted by the fact that you've used 3 different if/else cases for the same semantic result?

Re: Python Idioms [pdf]

#46
post #44

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…

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…

Logged in to post basically the same comment, then saw you already had. Essentially, no one who knows what they're doing in Python would write the function that way.

Re: Python Idioms [pdf]

#47

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…

>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.

I agree with you, when I read that I think if name and pets and owners, what? All equal each other? Seems like an unfinished statement.

Re: Python Idioms [pdf]

#48

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…

I'm surprised by your definition for a function named is_digit_char. I'd expect such a function to be something like:

    return len(s) == 1 and s[0] in string.digits
Or

    return re.search('^\d$', s)
Then it can be used idiomatically. The function you defined I'd call parse_int:

   def parse_int(s)
     "Return a parsed integer from 's' or None if it's not an int."""
      ...
Which would then be used as:

   i = parse_int(s)
   if i is None:
     ...your function definition...
$0.02.

Re: Python Idioms [pdf]

#49
post #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…

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.

you never use gettext in REPL :) and it's common to use '_' as gettext. Less typing, more readable strings. If you don't believe me, you should believe Alex Martelli [1], a random Python developer [2] or just read Official Python documentation [3] which recommends assignign gettext.gettext to '_'...

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

http://stackoverflow.com/a/1739541/720077

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

[3]: http://docs.python.org/2/library/gettext.html

Post reply on HN