r/Python • u/kracekumar • Jun 23 '14
Writing better python code
https://gist.github.com/kracekumar/09a60ec75a4de19b346e14
u/Husio Jun 23 '14
Although very old, still contains a lot of important examples http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html
11
u/nofunallowed98765 Jun 23 '14
Some other links:
Writing Idiomatic Python (Most of the example are included in that page, but there's more)
Writing Idiomatic Python Videos (Still a WIP)
Anyone has more?
1
4
u/mariox19 Jun 23 '14
joined_lower for functions, methods, attributes
joined_lower or ALL_CAPS for constants
StudlyCaps for classes
camelCase only to conform to pre-existing conventions
Attributes: interface, _internal, __private
I grew up on Java, which took Small Talk's camel case convention, so I'm just wondering: what's wrong with camel case anyway? The "blessed" coding convention in Python is the one thing I don't quite get. Is there an argument for underscores?
I swear I am not trying to start a flame war. It's just that I'm wondering if the preference is completely arbitrary or not.
8
u/fireflash38 Jun 23 '14
Pretty sure most preferences with this are kind of arbitrary. I think the idea is to make it similar to natural language with _ in lieu of a space.
7
u/cdcformatc Jun 23 '14
It is style and by definition style is subjective and completely arbitrary. You should write your code consistently no matter what the style is. In a team environment you should match the style used in the rest of the codebase. These style guides are just best practices, as they have been fought over for a long time. To this day people fight over where the braces go in C code, so having a unified "Python style" is nice.
2
u/gsnedders Jun 23 '14
Both have pros and cons. You can argue it to death which is better — the more important thing in general is consistency.
12
u/steve_no Jun 23 '14
The normal code "is" example seems strange. I think the non-pythonic thing most programmers do with respect to "is" is not using it, for example:
if a == None:when they should be doing:
if a is None:10
u/erewok Jun 23 '14 edited Jun 23 '14
Correct me if I'm wrong here, but I thought:
if a is None...Is asking if
aandNone(the singleton value) point to the same memory space. It's not asking if they're equivalent; it's asking if they are the same actual thing.Thus,
isis not the same as equivalence how we usually think of it (double equals).That's why setting a default value of
Noneis so useful in function definitions: there's only oneNoneand your function value either is that thing or it's not. It's never going to be likeNoneenough to pass for it.5
u/fuzz3289 Jun 23 '14
You sir are correct. Though "memory location" isnt a great way to say it. I would say:
The is operator returns true if both names are bound to the same object instance.
Since the "names" wont share a memory location.
3
u/zahlman the heretic Jun 23 '14
They certainly do "point to" the same memory location. But that's horribly un-Pythonic terminology.
3
u/erewok Jun 23 '14
Funny enough, I was curious about how the Python built-in
callablewas implemented just now and I stumbled on this page with the following quote:Every object has an identity, a type and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory. The ‘is‘ operator compares the identity of two objects; the id() function returns an integer representing its identity.
3
u/fuzz3289 Jun 23 '14
"You may think of it as" is important. The identity is actual a hash of the name in a lookup table.
Not to argue or anything, just want to emphasize that you cant actually deal with memory or memory locations directly in python.
1
1
u/rcxdude Jun 24 '14
Actually, the identity in Cpython is just the memory address of the object (literally casting the pointer to an int). It doesn't have to be according to the language though.
1
u/fuzz3289 Jun 24 '14
https://docs.python.org/3.3/reference/datamodel.html
Interesting, I didn't realize that it was just a direct address. Thanks for the correction.
3
u/erewok Jun 23 '14
...bound to the same object instance.
This is a nice, concise description. Thanks for adding it.
2
u/fuzz3289 Jun 24 '14
Thanks! Alot of people tend to forget the beautiful simplicity of python, just objects and names.
2
u/metaphorm Jun 23 '14
the "is" keyword can be dangerous if you don't understand what it really does though, which is a common problem for beginners.
in your example, its absolutely correct, because None is a singleton so any reference to None refers to the same instance of None. in general though, is checks for object reference equality (rather than value equality) and can produce unexpected results if you use it when you really meant to check value equality.
0
u/kracekumar Jun 23 '14 edited Jun 23 '14
isis used withTrue, False, None. If is used for string comparision there are serious drawbacks.a is Noneworks because of singleton.Most people try
>>>'foo' is 'foo'and it works. When they store the result in db and retrieve the valueiscomparison will fail.6
u/zahlman the heretic Jun 23 '14
Using
iswithTrueandFalseis a serious code smell. If there's any possibility that the value is of some type other thanbool, why don't you want to handle it in the default way? And if there isn't, "simple is better than complex" applies.1
u/alexanderpas Jun 24 '14
If I read this correctly,
isshould be considered part of the same token as the singleton.if • a • is None:instead of
if • a • is • None:0
u/pymag09 Jun 23 '14 edited Jun 23 '14
I think
if not a:
is better15
u/pbaehr Jun 23 '14
Depends. Could yield a false negative if a can be 0 or an empty string and that's not what you are interested in testing for.
6
u/bheklilr Jun 23 '14
I also prefer the explicit
if a is None, since it signals my intent better. I honestly try to only useif a:when a is a boolean, since I don't want to have to remember how__bool__is implemented for every type out there. In my opinion, explicit is better than implicit for being able to read your own code in a month's time.2
u/pymag09 Jun 23 '14 edited Jun 23 '14
Sorry may be I did not understand you but
when we work withNoneor numbers
we can be sure thata=None or 0 bool(a) = False bool(not a) True a=1 or -1 bool(a) = True bool(not a) FalseI have checked
bool('')just right now in python3 and got False.bool('hhh')= True.Can you give an example when issue that you described may occur?
5
u/pbaehr Jun 23 '14
For example, if I have a variable which is initialized as None and later want to find out if it was set, I might want to check and see if it was still None. If it's not, I want to do something.
if a is not None: do_something()If I rewrite that as:
if not a: do_something()do_something will also be called if a was initialized, but to a blank string, which was not the intention. Lots of types have some concept of a "false" value. As /u/steve_no points out in another comment: 0, '', [], {}, midnight all evaluate to False.
1
3
u/steve_no Jun 23 '14
if not a:
will also be True when a is 0, '', [], {}, or a datetime.time of midnight
6
Jun 23 '14
I'm sorry but a lot of these look like they're directly ripped from Raymond Hettinger's talk on pythonic conventions.
1
u/kracekumar Jun 23 '14
I addressed lot of common cases. It wasn't rip off the tutorial. I have watched lot of talks by core python devs, read writing idiomatic python code, python cookbook et all. Talk appeared last year, but there are blog posts and snippets which predates the talk. Does that mean Raymond Hettinger copied ? http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html http://python.net/crew/mwh/hacks/objectthink.html
7
u/oconnor663 Jun 23 '14 edited Jun 23 '14
Is foo[:] really the Pythonic way to copy a list?
Edit: In Python 3, lists have their own .copy() method.
3
2
u/imrobert Jun 23 '14
Yeah, I noticed that too. It seems like the "normal" way has the advantage of being clearer more concise.
2
u/velit Jun 23 '14
The only downside is the "normal" way is incorrect (or correct depending on the situation). Point being they're not the same thing.
2
u/imrobert Jun 23 '14
Ah, that's my bad. For those wondering what the difference is, this should clear it up:
Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> a = [1, 2, 3] >>> b = a >>> id(a) 4472029056 >>> id(b) 4472029056 >>> c = a[:] >>> id(c) 44720785604
u/velit Jun 23 '14
I prefer newList = list(old_list)
Communicates intent better
6
u/poo_22 Jun 23 '14
Copy is very literal already, I argue that semantically it does not get better.
1
u/velit Jun 23 '14
Copying is a detail of slicing syntax, it's not the purpose of it. With the list constructor it's immediately evident there's a new instance involved - that's what constructors do.
foo[:] also looks weird.
4
2
u/metaphorm Jun 23 '14
foo[:] is a totally respectable way to copy a list. it looks a little funny if you've never seen it, but it has the right semantics and does exactly what you would expect when slicing "from the beginning to the end". it does, however, rely on the programmer knowing that list slices produce copies.
2
u/zahlman the heretic Jun 23 '14
I dislike it because it's conceptually roundabout. "A list containing elements of x, from the beginning to the end" is similarly awkward in English compared to "a copy of x", or even "a list of the contents of x". Even if the analogous Python is terse.
2
u/metaphorm Jun 23 '14
I understand your point. I disagree that its conceptually roundabout. Once you understand that the slice operator really means "return a copy of this section of the list" it seems really natural.
1
u/ggtsu_00 Jun 24 '14
This is one of the few things I don't like about python is that slices make copies implicitly which goes against many python ideals. Lists are mutable, so you would expect operations on lists to only be references.
1
u/zahlman the heretic Jun 24 '14
Well, there seems to be precedent for what you're suggesting in NumPy...
0
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
Jun 23 '14
Counterhas 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
Counteris (it's like 3x slower thandefaultdict(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
Counterhas its own benefit. If the key doesn't exist it can return 0. There are lot of scenarios where this is super useful.4
3
u/r0m1 Jun 25 '14
For the function defaults, I would rather write:
def bar(names=None):
names = names or []
names.append(foo())
return names1
2
u/elb0w Jun 23 '14
Why is that called normal code? I would think pythonic is normal for python. I would call that bad code or unpythonic.
Also your default value for functions with a mutable type doesnt highlight the side effect that it causes and why you initialize to None.
4
u/kracekumar Jun 23 '14
Agreed normal code should have been named as bad code. Modified in the gist.
8
u/cdcformatc Jun 23 '14
250 + 6 is 256I don't know why this example is under normal code. No one does this it can't be considered normal. To test for equality, we usually use the equality operator.
1
Jun 23 '14
In fairness, -255 to +256 are kept in an identity map. Any equation that would output a number in that range instead pull it from the identity map.
I'm not saying it's the right way to do it, but it is a valid way to do if you expect your answer to never exceed that range.
1
u/Citrauq Jun 23 '14
Actually I think it's -5 to +256. More importantly, this is an implementation detail of cpython and may not be reliable in other implementations of python.
1
u/fuzz3289 Jun 23 '14
Just a suggestion OP your examples are very wordy. The exceas code is valid but it obfuscates the point youre trying to illustrate in alot of places. For example:
Superusers =functioncall
If len(superusers) > 0:
...Adds "real" context but obfuscates the boolean empty container idiom that youre trying to show. You dont need context to provide code examples. For instance I would say:
mylist = []
if (mylist):
print "mylist is empty!"Because even though that snippet has no practical application it clearly and succicently presents the concept.
More power to you for adding more educational materials to the python world. Keep it up.
0
u/kracekumar Jun 23 '14
Next time will write as blog post rather than code only show case.
1
u/fuzz3289 Jun 23 '14
Not even necessarily that. Just dont worry about being so specific with the examples. Make them as small and digestible as possible.
1
u/poo_22 Jun 23 '14
If they're using python3 then why prefix the strings with u? They are unicode by default afaik.
1
u/gthank Jun 23 '14
Support 2 and 3 from the same codebase, if for some reason you don't want
from __future__ import unicode_literals.0
3
u/unholysampler Jun 23 '14
The links title says that the examples were taken from a talk you gave. That's fine, but without the context that was being provided by you in person, the list seems very disjointed.
Most of the examples are alternate ways to write the same thing. However, some are examples of bugs or common gotchas. There is nothing there to point out when the "normal" code is actually wrong.
2
Jun 23 '14
What's he doing under "Counting Condition"? Does if list return False for a zero-length list, or only if the named list doesn't exist?
4
2
1
Jun 23 '14
Nice list, way to spread the good word. I've been writing python for 2 years now and learned a few new things from this. Thanks!
1
Jun 23 '14
See a lot of complaints in this thread, just wanted to say thanks because this has helped me out a lot!
1
1
Jun 23 '14
That's a nice list for Python beginners! Depending on the context, one thing I maybe wouldn't want to do is:
from collections import namedtuple
Person = namedtuple('Person', ['name', 'email'])over
class Person(object):
def __init__(self, name, email):
self.name = name
self.email = emailin the section
https://gist.github.com/kracekumar/09a60ec75a4de19b346e#dot-accessors
If find that working with classes a little bit "cleaner" in terms of keeping track of what is going on; also for extensibility, esp. when you add instance methods
1
Jun 23 '14
I like that namedtuples are immutable, and you can subclass them:
class Person(namedtuple('Person', ['name', 'email'])): passif you want to add methods to it. I like it for value objects, although it's obviously not the prettiest syntax.
1
u/ddungtang Jun 24 '14
I would say that some comparisons are not correct as whatever is under Bad code is not doing what it is supposed to, basically just wrong code. For example, copying of the list, using is for comparison, etc.
1
u/pymag09 Jun 23 '14
If you don't mind I can append to your list several items more
You can revert, for example, string just using slice
print(s[::-1])```
You can check condition in one line
``` i = 3
print(i if i < 5 else 0)```
or another if trick
``` condition = ['Error', 'OK']
value = 1
print(condition[bool(value)])```
As long as pyhton does not have switch construction you can use somthing like this
``` choice = 'i'
print({'i': 1, 't': 4, 'j': 22}[choice])```
2
u/BryghtShadow Jun 23 '14
You messed up the code formatting.
s = 'qwerty' print(s[::-1]) i = 3 print(i if i < 5 else 0) condition = ['Error', 'OK'] value = 1 print(condition[bool(value)]) choice = 'i' print({'i': 1, 't': 4, 'j': 22}[choice])1
u/pymag09 Jun 23 '14 edited Jun 23 '14
You messed up the code formatting.
Sorry. I noticed that but I follow "formating guide"
Lines starting with four spaces
are treated like code:if 1 * 2 < 3: print "hello, world!"After posting I understand that empty string before and after code block required.
1
u/SilasX Jun 23 '14
Am I the only one here who hates implicit casting to booleans? It seems more with the Zen of python to prefer
if len(z) > 0
to
if z
even though the latter is much shorter.
1
u/ggtsu_00 Jun 24 '14 edited Jun 24 '14
There is no implicit cast, it is simply implemented as a nonzero operator which is defined for all built in types. 0 is defined for any domain such that x = x + 0.
Lists have a zero that is the empty list because x + [] = x therefore [] is zero in the list domain. Same with empty string.
If statements doesn't ask for true or false, it asks for if zero or nonzero. Remember that booleans types didn't exist in python until around version 3. In version 2, True and False are simple macros for 1 and 0.
0
u/SilasX Jun 24 '14
Potato, potahto. I don't like the use of implied truthiness where a boolean operator would be more explicit.
0
-6
u/ericanderton Jun 23 '14 edited Jun 23 '14
if a < b < c:I'm sorry, but that has a serious smell. This means something entirely different in most every other language. It's not unreasonable to expect binary operators to evaluate left-to-right in all circumstances, so why would using this syntax quirk for comparison operators be a good practice?
In keeping with the rest of this style guide, I would much prefer something akin to:
if is_sorted_or_some_other_function([a, b, c]):...as it's perfectly clear what's happening with this.
6
u/cdcformatc Jun 23 '14 edited Jun 23 '14
Is this a troll? You really think that the first example is bad code? You prefer to check a list that doesn't exist and has no meaning to using comparison operators? As to your fix,
sortedreturns a sorted list, it does not check if the list is sorted.So if by perfectly clear you mean perfectly clear that it doesn't do what the original code is intending, then yes, it is quite clear.
1
u/ericanderton Jun 23 '14
Sorry, i was unaware that 'sorted' was already in the Python standard lib. I revised my remark to make it more clear what I was getting at.
Basically my beef is that the back-to-back comparison operators is a special case when stacked up against other operators in the language. It doesn't read well when your engineers are also experienced in Javascript, C, Go, and everything else.
Consider this: if a + b < c:
We take this as being equivlaent to "(a + b) < c", right? So why does "a < b < c" get expanded to "a < b and b < c" ? It's terribly inconsistent.
5
u/cdcformatc Jun 23 '14 edited Jun 23 '14
It's special Python syntax. List comprehensions don't exist in Javascript or C either but you should still use them. When used correctly they add readability to the code. If you don't use any of the Python-specific syntax and idioms your Python code will suffer as a result. Do you also put semicolons on the ends of lines? When writing Python, you use Python syntax, you do not use Javascript or C or Go syntax. I hope the engineers should be able to adapt to something different.
Anyone who has done any math will know what
a < b < cmeans. I'd hope an engineer would have a decent math background.As to your example, I would never rely on the inherent operator precedence rules, so I would write
(a + b) < cfrom the beginning, since it removes any and all ambiguity.If you want to do something as simple as check if a number is between two other numbers, why would you construct a list, and check if that list is sorted? That is just some backwards thinking and frankly a terrible idea. Someone looking at that code for the first time will have no clue what is going on.
1
u/ericanderton Jun 23 '14
I see where you're coming from. And you're right: If we're talking about Python code, we should consider all the nice things that the language brings to the table.
At the same time, anyone reading our code shouldn't have to second guess if an expression is a mistake or not. After all, clarity isn't some universal truth or consistent quantity across the engineering spectrum; it's fuzzy. Hence why I say that this particular syntax 'has a smell', since even an experienced Python developer might have to think twice when reading this. It's that potential to second-guess that gives me pause here. In the end, it's not up to whether or not I might not understand this particular use of comparison operators; it's everyone else that's hacking on my projects that I worry about.
4
u/gthank Jun 23 '14
It's a standard math construct from a very basic level; even non-programmers reading that code would have a very good guess as to what it does. Just because other languages can't be bothered to implement something so nice doesn't mean we should avoid it in Python.
3
u/zahlman the heretic Jun 23 '14
even an experienced Python developer might have to think twice when reading this
Realistically, only one who has recently been doing work on the side in another language. (It helps that the behaviour shown in other languages is basically never desired.)
0
Jun 23 '14
[deleted]
3
u/cdcformatc Jun 23 '14
I object to
if super_users:overif len(super_users) > 0:There is a huge difference between an empty list andNone. If you want to check that the length of the list is greater than zero you should... just do that.A lot of this reads like "Abuse syntax to make your code look more Pythonic" and treats Pythonic like some lofty goal. A lot of "Pythonic" code is just harder to read, it isn't an end in itself.
6
u/zahlman the heretic Jun 23 '14
If
super_userscan be either an empty list or None, and your code cares about the difference, it should be explicitly checking foris Nonefirst. "the length of the list is greater than zero" is an unusually verbose way of saying "the list is not empty" in English; the analogous statement holds for Python, except that we don't have an actual keyword for "empty".7
u/quasarc Jun 23 '14
I object to
if super_users:overif len(super_users) > 0:There is a huge difference between an empty list andNone.Both of these tests can only be used if you know that
super_usersis a list and notNone.Using
if super_users:is not abusing syntax, it just uses the intended and well-known fact that non-empty sequences are true. (It's also recommended by the style guide PEP8.)1
u/turtle_with_dentures Jun 23 '14
Thank you. Ran in to this exact issue earlier when a JSON request was returning an empty list.
1
u/metaphorm Jun 23 '14
I agree with you. I think the 'any' function is intended primarily for dynamically populated lists where you don't know before runtime if it will be empty or contain an arbitrary number of items. If you know in advance which items to check its definitely better to use an 'or' chain.
46
u/robin-gvx Jun 23 '14
I have problems with some of these.
Replacing
a or b or cbyany([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
KeyErrorjust to raise anotherKeyError? Just let it bubble up.I kinda hate
namedtuplebecause 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.