Live data from Hacker News

Python best practices

fantascienza.net

21–30 of 41 posts

Re: Python best practices

#21
post #15

> if x is None: ... > if items is None: ... None's truth value is false, so the above are equivalent to: if x: ... if items: ... Empty sequences and mappings are also considered false, so you don't need to if len(items): ... Instead, you should if items: ... On a side note, does it annoy the hell out of anyone else that a sequence's length is len(foo) instead of foo.length() (or size, count, etc)?

There's a reason why "if x is None" is idiomatic when "if not x" is shorter: >>> x = '' >>> if x is None: ... print 'x is None' ... >>> if not x: ... print 'x is empty' ... x is empty

Good point. I was only thinking of sequence types, and failed to see that it would break with strings. I also somehow forgot to include "not" in the if statements! Pretty sad for a first post...

Re: Python best practices

#22

> if x is None: ... > if items is None: ... None's truth value is false, so the above are equivalent to: if x: ... if items: ... Empty sequences and mappings are also considered false, so you don't need to if len(items): ... Instead, you should if items: ... On a side note, does it annoy the hell out of anyone else that a sequence's length is len(foo) instead of foo.length() (or size, count, etc)?

bool(x) may sometimes do more than x is None. If x is not None, then truth value is determined by calling __nonzero__ or __len__. For an ordinary sequence type that's fine, but some years ago I had code like this:

if not self.db: self.db = bsddb.hashopen(...).

I just couldn't find out why my process spent valuable seconds apparently reading in the entire bsddb database into memory at random times -- but that's because bool(self.db) above turned into len(self.db.keys()) != 0

Re: Python best practices

#23
post #9
post #3

My comments: > x=5 || x = 5 Noooo. That first one is backwards. Extraneous spaces annoy me to no end. Makes it a pain to search for things too. On the other hand, using newlines to break things up at commas for example, is great. But that's not applicable here. > class fooclass: ... || class Fooclass(object): ... Is this a joke? > d = dict() || frequences = {} How can you say that longer names are always better? (Is…

> class fooclass: ... || class Fooclass(object): ... Is this a joke? No... it is generally recommended that class names are capitalized, and any classes you create are supposed to inherit from object. This mainly comes into effect when using super(). In Python 3K, I'm pretty sure that all classes will inherit from object without having to explicitly say it.

More importantly property getters will silently do nothing in old-style classes and just let the attribute setting through without calling the setter, while getters work fine.

Re: Python best practices

#24
post #14
post #7

Earlier quoted context omitted.

And look how complicated they make it. Sometimes spaces, sometimes not, how confusing. And tell me that their "Use spaces around arithmetic operators" example doesn't make you want to puke: i = i + 1 submitted += 1 x = x * 2 - 1 hypot2 = x * x + y * y c = (a + b) * (a - b) Who writes like that?? I very strongly disagree.

"Who writes like that??" The authors of: BitTorrent: https://develop.participatoryculture.org/trac/democracy/brow... Django: http://code.djangoproject.com/browser/django/trunk/django/ut... Pylons: http://pylonshq.com/project/pylonshq/browser/pylons/util.py Twisted: http://twistedmatrix.com/trac/browser/trunk/twisted/python/u...

Not one of those has more than a couple mathematical operators per line. Very misleading examples. Try again.

Re: Python best practices

#25
post #8
post #7

Earlier quoted context omitted.

And look how complicated they make it. Sometimes spaces, sometimes not, how confusing. And tell me that their "Use spaces around arithmetic operators" example doesn't make you want to puke: i = i + 1 submitted += 1 x = x * 2 - 1 hypot2 = x * x + y * y c = (a + b) * (a - b) Who writes like that?? I very strongly disagree.

I do. I think it looks a lot better and more clear. It certainly looks a lot like what I would write down on paper, and that is one of the inherent qualities of Python in general.

You write with big gaps like that? No you don't...

Re: Python best practices

#26
post #16
post #7

Earlier quoted context omitted.

And look how complicated they make it. Sometimes spaces, sometimes not, how confusing. And tell me that their "Use spaces around arithmetic operators" example doesn't make you want to puke: i = i + 1 submitted += 1 x = x * 2 - 1 hypot2 = x * x + y * y c = (a + b) * (a - b) Who writes like that?? I very strongly disagree.

I do all of these (even in interactive shell) except I have a weak spot for this sort of notation: i+=2

Why do you waste time with doubling the number of characters you have to type at the interactive shell?

Re: Python best practices

#27
post #12

This is an excellent overview of how Python is usually written by people who write (and read) a lot of it. I hardly ever see coding conventions documents that do such a good job of capturing the popular conventions without inserting quirky personal preferences. I clicked through expecting something to point and laugh at, but was pleasantly surprised!

This has a lot of quirky personal preferences, you just don't see them because they match yours:)

Re: Python best practices

#28
post #5
post #3

My comments: > x=5 || x = 5 Noooo. That first one is backwards. Extraneous spaces annoy me to no end. Makes it a pain to search for things too. On the other hand, using newlines to break things up at commas for example, is great. But that's not applicable here. > class fooclass: ... || class Fooclass(object): ... Is this a joke? > d = dict() || frequences = {} How can you say that longer names are always better? (Is…

Though I am a lowly Python noob, I'll tell you it's generally very bad practice to use a mutable as a default argument value. The reason is that a function's default is only ever initialized once. Case in point: >>> def f(l=[]): ... l.append(0) ... print l ... >>> f() [0] >>> f() [0, 0] >>> f() [0, 0, 0] Unless you 1) actually want the appearance of a 'static' local variable or 2) are really careful to make a copy of…

I always took that as a case against mutating arguments, not against defaults. You still have the same problem if you pass in an argument:

>>> MY_CONSTANT = ['foo', 'bar', 'baz'] >>> def f(l): ... l.append(0) ... print l ... >>> f() ['foo', 'bar', 'baz', 0] >>> f() ['foo', 'bar', 'baz', 0, 0]

I would've rewritten f as:

  def f(l=[]):
      print l + [0]
...unless you specifically want f to mutate its caller's variables and have documented it as such.

Generally, I try to avoid mutating objects unless a.) I just created the object within the function or b.) it's specifically intended as a "long lived" data structure, i.e. something that survives multiple user interactions. For everything else, I try to use the non-mutating operations (slicing, concatenation, list comprehensions) or make an explicit copy of the argument.

Re: Python best practices

#29
post #7

Earlier quoted context omitted.

> Extraneous spaces annoy me to end. It is recommended in the "official" python style guide to surround the assignment operator with a single space: http://www.python.org/dev/peps/pep-0008/

And look how complicated they make it. Sometimes spaces, sometimes not, how confusing. And tell me that their "Use spaces around arithmetic operators" example doesn't make you want to puke: i = i + 1 submitted += 1 x = x * 2 - 1 hypot2 = x * x + y * y c = (a + b) * (a - b) Who writes like that?? I very strongly disagree.

I do. I find that code with the spaces around assignment and arithmetic operators is way easier to read.

Re: Python best practices

#30
post #8

Earlier quoted context omitted.

I do. I think it looks a lot better and more clear. It certainly looks a lot like what I would write down on paper, and that is one of the inherent qualities of Python in general.

The one place that I don't follow the guideline (unless it's the guideline and I just don't know it... it rarely comes up, so I haven't bothered to check) is on array indices. I do write: a[i+1]

Same here. I conceptualize it as part of a code compactness strategy: array indices are part of the same item, and thus I use syntax (like yours) that suggests inlining.
Post reply on HN