Live data from Hacker News

Python idioms I wish I'd learned earlier

prooffreaderplus.blogspot.com

71–80 of 174 posts

Re: Python idioms I wish I'd learned earlier

#71
post #57
post #54

Earlier quoted context omitted.

Shouldn't unhex() just be int(s, 16)? Not sure what it adds, but I don't quite understand it yet and perhaps there's something magic in the context of MIME quoted printable that I'm missing.

That is an excellent point! Based on my reading, there's nothing magic. The context is: elif i+2 I tweaked it to new = new + bytes((int(line[i+1:i+3], 16),)); i = i+3 and the self-tests still pass. (I also changed the 16 to 15 to double-check that the tests were actually exercising that code.) It's not part of the public API, so it looks like it can simply be removed. Do you want to file the bug report? Or perhaps it…

> It's not part of the public API, so it looks like it can simply be removed.

https://docs.python.org/3/library/functions.html#int

So that is actually standard. Maybe I just don't know what you mean by public API though.

Re: Python idioms I wish I'd learned earlier

#72
post #71
post #57

Earlier quoted context omitted.

That is an excellent point! Based on my reading, there's nothing magic. The context is: elif i+2 I tweaked it to new = new + bytes((int(line[i+1:i+3], 16),)); i = i+3 and the self-tests still pass. (I also changed the 16 to 15 to double-check that the tests were actually exercising that code.) It's not part of the public API, so it looks like it can simply be removed. Do you want to file the bug report? Or perhaps it…

> It's not part of the public API, so it looks like it can simply be removed. https://docs.python.org/3/library/functions.html#int So that is actually standard. Maybe I just don't know what you mean by public API though.

"it" == "unhex", not "int"

Re: Python idioms I wish I'd learned earlier

#73
post #72
post #71

Earlier quoted context omitted.

> It's not part of the public API, so it looks like it can simply be removed. https://docs.python.org/3/library/functions.html#int So that is actually standard. Maybe I just don't know what you mean by public API though.

"it" == "unhex", not "int"

Oh, right! I had not read the sentence correctly.

Re: Python idioms I wish I'd learned earlier

#74
post #13

One of my favorites: >>> print "* "* 50 to quickly print a separator on my terminal :) Previous discussion on python idioms from 300 days ago: https://news.ycombinator.com/item?id=7151433

That's cute, but the result of a bad design decision. Python overloads "+" as concatenate for strings. This also applies to lists. So [1,2,3] + [4,5,6] yields [1,2,3,4,5,6] This is cute, but not what you want for numerical work. Then, viewing multiplication as repeated addition, Python gives us [1,2,3]*4 yields [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3] This is rarely what was wanted. Then there's numpy, which has its own…

* on lists can also mean elementwise multiplication, dot or cross product if you treat them as vectors. There's no way to choose the objectively best meaning. I'd even argue that vector math isn't the most popular use for lists in python, not because of + and * semantics, but because of performance.

So it was good design decision not to bother with math semantics for general use datastructure.

And besides Python has nice general syntax for elementwise operations if you don't care about performance:

    [x*y for (x,y) in zip(xs,ys)]
I agree it would be better not to implement + for lists at all.

Re: Python idioms I wish I'd learned earlier

#75
Most of these idioms actually make me sad.

When I first started using Python around 1999, it didn't even have list comprehensions. Code was extremely consistent across projects and programmers because there really was only one way to do things. It was refreshing, especially compared to Perl. It was radical simplicity.

Over the decade and a half since then, the Python maintainers have lost sight of the language's original elegance, and instead have pursued syntactical performance optimizations and sugar. It turns out that Python has been following the very same trail blazed by C++ and Perl, just a few years behind.

(At this point Python (especially with the 2 vs. 3 debacle) has become so complex, so rife with multiple ways to do even simple things that for a small increase in complexity, I can just use C++ and solve bigger problems faster.)

Re: Python idioms I wish I'd learned earlier

#76
Some comments:

1. Am I the only one that really loves that `print` is a statement and not a function? Call me lazy, but I don't mind not having to type additional parentheses.

5. Dict comprehensions can be dangerous, as keys that appear twice will be silently overridden:

  elements = [('a', 1), ('b', 2), ('a', 3)]
  {key: value for key, value in elements} == {'a': 3, 'b': 2}
  # same happens with the dict() constructor
  dict(elements) == {'a': 3, 'b': 2}
7. I see

  D.get(key, None)
way too often.

8. Unpacking works in many situations, basically whenever a new variable is introduced.

  for i, el in enumerate(['a', 'b']):
    print i, el

  {key: value for (key, value) in [('a', 1), ('b', 2), ('a', 3)]}

  map(lambda (x, y): x + y, [(1, 2), (5, -1)])
Note: the last example (`lambda`) requires parentheses in `(x, y)`, as `lambda x, y:` would declare a two-argument function, whereas `lambda (x, y):` is a one-argument function, that expects the argument to be a 2-tuple.

Re: Python idioms I wish I'd learned earlier

#77

Earlier quoted context omitted.

$ 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

Use `textwrap.dedent()`?

I normally just do this for multiline strings:

    s = "\n".join(["one","two","three"])

Re: Python idioms I wish I'd learned earlier

#78

Most of these idioms actually make me sad. When I first started using Python around 1999, it didn't even have list comprehensions. Code was extremely consistent across projects and programmers because there really was only one way to do things. It was refreshing, especially compared to Perl. It was radical simplicity. Over the decade and a half since then, the Python maintainers have lost sight of the language's orig…

Are we reading the same article, though?

It's certainly up for debate whether named tuples and enums, various kinds of metaprogramming and decorators might be making the language more complex for fairly little gain... but this article talks about the `enumerate` function, about string formatting and dictionary comprehensions. Simple, straightforward stuff with no downsides.

Re: Python idioms I wish I'd learned earlier

#79

Earlier quoted context omitted.

$ 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

Use `textwrap.dedent()`?

Dedent is nice, but then you still have to deal with removing single newlines (e.g. for error messages) and removing leading and trailing spaces. Ultimately nothing more than `re.sub(r'[^\n]\n[^\n]', '', textwrap.dedent(s).strip())` but kind of annoying to have to throw this in your code all over the place.

Re: Python idioms I wish I'd learned earlier

#80
post #61

"Because I was so used to statically typed languages (where this idiom would be ambiguous), it never occurred to me to put two operators in the same expression. In many languages, 4 > 3 > 2 would return as False, because (4 > 3) would be evaluated as a boolean, and then True > 2 would be evaluated as False." The second half of this is correct, but it has nothing to do with whether the language is statically or dynami…

It's not just a tweak to the parser, and it does have to do with the type system, but you're right that it's not about static typing. The issue is that there are languages (like C) where typing is static but weak, so e.g. booleans are also integers and can have integer operations like '>' applied to them. In other words, the problem is that in C True == 1 and 1 > 2 is a valid expression. In Python, which has strong(e…

In fact, Python just has a non-binary AST with regard to operators, i.e. the expression "a https://docs.python.org/3/library/ast.html#abstract-grammar for details.
Post reply on HN