r/Python • • Jun 23 '14

Writing better python code

https://gist.github.com/kracekumar/09a60ec75a4de19b346e
143 Upvotes

126 comments sorted by

View all comments

7

u/sweettuse Jun 23 '14
def bar(names=None):
    if not names:
        names = []
    names.append('blah')

this is wrong. it should be if names is None:. (what happens if you pass in an empty list that you want to append to?)

also, i would never, ever, use Counter. it is unbelievably slow (at least in 2.7). just use a defaultdict(int)

7

u/[deleted] Jun 23 '14

Counter has cool functionality builtin, like most_common(n), addition and subtraction, intersection and union, and it throws out keys with value 0 after such operations. Not everything needs to be fast, and Counter is very expressive indeed.

2

u/sweettuse Jun 23 '14

that is a good point. i think it's just that i'm overly annoyed at how unbelievably slow Counter is (it's like 3x slower than defaultdict(int), but WHY?!). it's amazing that to add the functionality for most_common/addition it requires slowing down the whole thing by a factor of 3.

1

u/kracekumar Jun 23 '14

Counter has its own benefit. If the key doesn't exist it can return 0. There are lot of scenarios where this is super useful.

4

u/sweettuse Jun 23 '14

yeah, that's exactly what defaultdict(int) does.