r/Python • • Jun 23 '14

Writing better python code

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

126 comments sorted by

View all comments

46

u/robin-gvx Jun 23 '14

I have problems with some of these.

  • Replacing a or b or c by any([a, b, c]). Is that really more Pythonic? If they'd been in an iterable already I'd say yes, but now not so much.

  • Catching KeyError just to raise another KeyError? Just let it bubble up.

  • I kinda hate namedtuple because it's such a hack, but maybe that's just me.

  • Also, I'd say the opposite of Pythonic code is not normal code. Un-Pythonic or unidiomatic, or maybe something about newbies.

7

u/pstch Jun 23 '14

Could you expand on why "namedtuple" is such a hack ?

9

u/robin-gvx Jun 23 '14

Because it's implemented as piecing together a string that contains a class statement and compiling that to obtain the tuple subclass (see source).

4

u/[deleted] Jun 23 '14

Goofy implementation, doesn't need to be written that way

7

u/rcxdude Jun 23 '14

see here for why it's kept that way.

4

u/NYKevin Jun 23 '14 edited Jun 24 '14

TL;DR: Because calling type() correctly is apparently too hard:

It is a key feature for named tuples that they are exactly equivalent to a hand-written class.

So is a call to type() if you know what you're doing.

EDIT: If you examine the official code more closely, you'll note they had to write extensive string-escaping to prevent the user from passing an argument like '); import os; os.system("/bin/sh"); ('. Quite frankly, I will not be touching that with a ten-foot-pole any time soon.

EDIT2: I tried, but they wouldn't listen to me. Oh well.