Live data from Hacker News

Python idioms I wish I'd learned earlier

prooffreaderplus.blogspot.com

41–50 of 174 posts

Re: Python idioms I wish I'd learned earlier

#41
post #25
post #22

This is something I do instead of writing a long if-else: opt = {0: do_a, 1: do_b, 3: do_b, 4: do_c} opt[option]()

Do you consider that to be idiomatic? I've been out of touch with the a Python community for a few years, but back then I wouldn't have considered that remotely idiomatic, and if I was on a team writing software, I would have argued that we shouldn't be writing code like that.

Besides you can write code like this

   s = {'square': lambda x: x **2, 'simple': lambda x: x, 'cube': lambda x: x ** 3}

   s.get('square', lambda x: 0)(10)
   s.get('nonexistent', lambda x: 0)(10)
Substitute lambdas for real functions and you have a powerful switch case.

Re: Python idioms I wish I'd learned earlier

#42
post #13

Earlier quoted context omitted.

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…

Even worse IMHO is the semantics of strings being implicitly iterable. Often it ends up that you're intending to iterate over something for item in orders: do_something_with(item) So if `foo` is usually `[Order(...), Order(...), ...]` but due to a bug elsewhere, sometimes `foo` is "some string". Then you get a mysterious exception somewhere down in `do_something_with` or one of its callees at run time, and all becaus…

I use "for c in s", to read characters in a string, pretty often. Here's an example from Python3.2's quopri.py:

    def unhex(s):
        """Get the integer value of a hexadecimal number."""
        bits = 0
        for c in s:
            c = bytes((c,))
            if b'0' 
Here's another example of iterating over characters in a string, from pydoc.py:

    if any((0xD800 
It seems like a pretty heavy-weight prohibition for little gain. After all, you could pass foo = open("/etc/passwd") and still end up with a large gap between making the bug and its consequences.

Re: Python idioms I wish I'd learned earlier

#43
post #24

Earlier quoted context omitted.

I personally don't like this style of using multiple strings. Makes radical changes of the text cumbersome. I think in most cases it's better to use triple quotes. And if the content of these variables isn't exclusively shown in the shell, you should use translation files anyway.

$ 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()`?

Re: Python idioms I wish I'd learned earlier

#45

Can someone direct me to a comparision of subprocess and os? I keep hearing subprocess is better, but have not really read any explanation as to why or when it is better. (I'm glad I'm not the only one who was thrilled to discover enumerate()!)

All explained here: https://www.python.org/dev/peps/pep-0324/

tl;dr

* Security (including avoiding holes like shellshock)

* Unification of process handling under one core library.

* Easier detection of errors in processes.

* Easier control of stderr/stdout.

* Universal newline support.

* Elimination of race conditions with .communicate()

Re: Python idioms I wish I'd learned earlier

#46

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()`?

Didn't know about textwrap, but this does not strike me as particularly lightweight. You really want built-in syntax for something like this.

Re: Python idioms I wish I'd learned earlier

#47
post #25

Earlier quoted context omitted.

Do you consider that to be idiomatic? I've been out of touch with the a Python community for a few years, but back then I wouldn't have considered that remotely idiomatic, and if I was on a team writing software, I would have argued that we shouldn't be writing code like that.

I've done this before, I think of it as a more powerful form of a switch statement. I'd love to hear why you think it's not ideal.

I don't think it's more powerful in any way than an if-elif-elif-else which, for what it's worth, I consider the Pythonic way.

Having said that, just because I consider something more Pythonic doesn't mean I prefer it. I've worked in a lot of languages over the years and still work in several in addition to Python. I really enjoy Python, but I prefer techniques that are more universal in many cases. For example, I prefer the idiom of looping over a list index to using Python's "enumerate" in most cases, because index looping is a common cross-language idiom and enumerate usually doesn't offer any benefit I value more than universal obviousness.

Other things such as Python's `for item in items` looping style are both VERY Pythonic and much nicer than, say, index looping, so I would almost always prefer such idioms.

The above switch -> function pointerish thing is clear to me from years of C/C++, but it is both less generally applicable across languages than if-elif... and less Pythonic, so I would prefer the if-elif... approach.

Obviously a matter of preferences, but since you asked....

Re: Python idioms I wish I'd learned earlier

#48
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…

This is because you're assuming 'array' is supposed to mean 'vector' (as in the linear algebraic vector). It isn't, and it's a list -- it's meant to be a container. In this case, add meaning concatenate and multiplication meaning self-concatenate multiple times makes sense.

Re: Python idioms I wish I'd learned earlier

#50
post #27
post #18

Earlier quoted context omitted.

But can any lisp dialect do: a = c ?

Given that lisps tend to use prefix notation, the example doesn't even translate meaningfully.

I assume the above was intended to be a Python expression. The answer, to the best of my knowledge, is "not really". There is no built in or reasonably standard function that lets you check simultaneously that a is less than b which in turn is greater than or equal to c. Not that we couldn't define one ad-hoc, although making it reusable in a way that's reasonably idiomatic might be a challenge...

Obviously, you can express it slightly more verbosely:

(and (= b c))

Post reply on HN