r/Python • u/_pep_8_ • Jan 01 '11
PEP 8 & Underscores
I opened the threading module documentation and saw a note at the top describing a change in the naming convention for functions from the Java inspired API in camelCase mixedCase to PEP 8 style recommended underscores. No deprecation of the old camelCase mixedCase names yet.
I’m a big fan of stylistic conventions and I basically follow PEP8, but I just do not like the use of underscores. I realize these types of preferences are as subjective as say liking the color red more than blue, but I’m curious to know how many other people just write their code following the naming conventions of languages like Java, C#, and Javascript libraries?
I came to Python from Perl and one of the things that attracted me to Python was readability. It read like pseudocode and I think a big part of that was because there wasn’t $, @, and % all over the place in addition to the removal of { and ;. I liked that I could write an if statement without wrapping it in parenthesis.
even better was I didn’t have to reach to the top row typing some of these symbols over and over again. Sure it seems like a small thing to just reach, but with some symptoms of RSI and doing it for many hours a day I think it really does incur a significant cost in comfort. I don’t like typing _ anymore than I like reaching up to type $.
I actually was sort of attracted to some of the standard library modules all lowercase convention. I know readability can be an issue here, but os.path.dirname is better than os.path.dirName or os.path.dir_name. You do really see the mix though of the different styles within the standard library. I know the primary argument for the underscore is readability, but I actually think the gap between dir and name is just too significant and when you are looking at a full page of names like this the underscores just begin to jump out as a pattern of white space. Maybe this comes from using too much camelCase mixedCase.
EDIT: Some people who may come across this post may be interested in a solution to the more serious issue of typing underscores - a pain and slow to type when you are doing it over and over and over again. I found an open source program today called AutoHotKey. Install that and then create a simple text file with a ".ahk" extension. Type "+space::Send _" into the file without the quotes and save. Double click to launch. Put in your startup folder. You can now type underscores pressing the shift + space key.
I am currently having some issues with the shift key sticking at times and thus typing undescores when I mean space. It doesn't seem to be keyboard dependent. So this may be a flaw in the software :( . Any other recommendations helpful.
3
u/akdas Jan 02 '11
Personally, I prefer dashes, meaning names-like-this. Of course, most programming languages, including Python, don't allow that, so I like underscores as a close substitute.
That said, bevem2 is absolutely right about adapting to the language you're using.
1
u/_pep_8_ Jan 02 '11
Yes, the dash is better than the underscore in that it breaks up the excessive white space of the underscore.
adapting to the language you're using.
I wonder what you do when you use Jython? Or what about the threading module inspired by Java. Here's an example of what you will see in the docs:
Note: Starting with Python 2.6, this module provides PEP 8 compliant aliases and properties to replace the camelCase names that were inspired by Java’s threading API. This updated API is compatible with that of the multiprocessing module. However, no schedule has been set for the deprecation of the camelCase names and they remain fully supported in both Python 2.x and 3.x.
Examples:
threading.current_thread()
threading.currentThread()
threading.RLock()
threading.BoundedSemaphore([value])
class threading.Timer
threading.setprofile(func)
threading.stack_size([size])
1
u/akdas Jan 02 '11
I wonder what you do when you use Jython?
That's a very good point. At some point, you will have mixed conventions, since you'd be using some functionality in Python's standard library and some functionality in Java's. Which style you'd use for code you write is tougher to decide. Perhaps it's a matter of whether you view the particular application as a Python program utilizing the Java's libraries, or as Java program that uses Python's syntax.
Or what about the threading module inspired by Java.
I'm not sure of the exact circumstances surrounding that, but it seems like a good idea to go with the PEP 8 style names, and it seems like something that should have been done from the beginning. After all, it is inspired by Java, but it isn't Java. (There's probably more to the story than that, so correct me if that's the case.)
1
u/_pep_8_ Jan 02 '11
I know its not Java and I am thankful its not! However, if you are going to use Java's CamelCase for class names, why not just go all the way. You've already introduced identifiers not separated by underscores.
Given Java's popularity there really is no point in deviating from a naming convention that works and it almost ubiquitous. People coming over from the language who know some of the libraries inspired by Java don't have to worry about mistyping a method name because its in underscores instead of mixecCase.
The people criticizing CamelCase and mixedCase as much more unreadable are really making a subjective argument. Its more readable to them. Maybe they can work their whole lives programming in Python, but even Python uses CamelCase so you have to get used to it. And widely used languages like Java and Javascript (libraries too like jQuery) and C# also use it.
Once you know your identifiers you probably aren't reading the whole thing anyway. Your brain probably sees the first few letters and knows what it is. The extra gaps created by underscores is just a distraction at that point disrupting your ability to grok the surrounding syntax. Your hands will also thank you for it.
0
Jan 04 '11 edited Jan 04 '11
Actually I don't see why threading.current_thread is even a callable. Maybe it's just a design decision, but there's no reason why threading.current_thread shouldn't be a property. Furthermore calling this function doesn't have any side-effects anyway.
3
u/yetanothernerd Jan 02 '11
camelCaseIsReallyUgly.
underscores_are_better
0
u/_pep_8_ Jan 02 '11
Well you need to qualify that. According to GVR in PEP8 underscores are "ugly!" whenever there are caps in it. In any case, PEP8 requires that you write "ugly" CamelClase for class names. But ultimately these are subjective opinions. Most of the "readability" arguments here are subjective supported by unrealistically long examples to make their case.
I've pointed out, in other comments, why I think mixedCase is more readable with code example that people actually use in the real world. The logical reason why underscores are more readable is they create a bigger white space gap between multiple words within an identifier. Yes, that is more readable but we don't really read code like we read the English sentences people are using around here and that extra whitespace gap becomes a nuisance.
A sentence in code is composed of various parts of different kinds of significance. I don't write "ifidentifier:" for an if statement. I write "if identifier:". I don't write "whileidentifier=1:", I write "while identifier = 1:". My brain parses it like this (if, identifier, :) or (while, identifier, =, 1, :). If I used underscores my brain would break it apart like this (while, a, long, identifier, with underscores, =, 1, :) because that's how our brains, from reading English all the time, are trained to chunk things and concidentally why people think its more "readable". Yet that readability is not a huge advantage in this context.
When you are looking at thousands of lines of this stuff a day you are creating a huge penalty by having to see your identifiers all over the place creating extra whitespace where you really don't the whitespace to be significant. Your brain is going to be able to grok the identifier from its first few letters anyway after some minimal exposure, but its very hard for your brain not to attach significance to notice the increased gaps from underscores because you are so trained to do it from normal reading.
13
u/bevem2 Jan 01 '11
I adapt to follow the recommended coding style for the language I'm using. You get used to it and it's best for everyone.
From PEP 8: "words separated by underscores as necessary to improve readability" so I think .dirname is fine since it's perfectly readable.
3
u/epicRelic Jan 02 '11
so I think .dirname is fine since it's perfectly readable.
What is a dirn ame?
4
4
u/justanotherbody Jan 02 '11
I agree that underscores between words is more readable. That being said, camel case saves a character a word, which can easily add 3 characters to the line. Not exactly game breaking, but there are days when it can be fscking annoying.
3
2
u/JimH10 Jan 02 '11
camel case saves a character a word
Yes, I came here to say this. Putting a line f code on a single line is typically better than on multiple lines
which can easily add 3 characters to the line
author_name_list = [author_name for author_instance.author_name in author_instance_list]is a lot of spaces, including the two around the equal sign
Not exactly game breaking
But if the line is already indented by a dozen spaces, it can easily cause you to run over onto the next line (especially if the line is commented).
Still, I generally follow PEP 8, although those parts I consider suboptimal.
1
u/hippocampe Jan 02 '11
should be written:
author_names = [author.name for author in authors]... these 'instance' and 'list' have no place.
2
u/JimH10 Jan 02 '11
... these 'instance' and 'list' have no place
Your opinion. Mine differs. I find them useful sometimes, particularly when revising the code weeks later.
In any event, it is a made-up example illustrating that there can be lots of spaces taken up on a line. My point remains correct.
0
Jan 04 '11 edited Jan 04 '11
Maybe it's opinion like you say but I have some suggestions:
author_instance
You already make distinction between ‘Author’ class (capitalized, camel-case) and ‘author’ instance (lowercase). Having ‘instance’ suffix seems redundant.
object_list vs objects
This seems like unnecessary implementation detail. Why do you care whether your collection is list, set or generator? I can see how in Python 3 (or Python 2.5+) when generator is the default, having an explicit in-memory data structure is worth noting, however in that example it really doesn't matter.
Actually I'd argue even that ‘author_names’ is redundant. Simply
names = (author.name for author in authors)should be sufficient. ‘author_names’ makes sense only if you have other names in given context (bird names, elephant names, socks names). And perhaps it's better to have smaller context rather than having explicit names.
1
u/JimH10 Jan 04 '11
Again, you seem not to have understood the point.
The point is that using underscores can add significantly to the length of a line, over using camel case.
As to the things you say about the code, in the first place it was an off the top of my head example, not an excerpt. In the second place, the code I had been working on earlier actually has two lists of names, so I need to distinguish between author_names and package_names. In the third place, I have a practice that when I have to revisit code to debug it a number of times (because the testing is exposing errors), I make the parts very explicit, anticipating that I may have to look at it weeks from not when another bug gets noticed and I remember less what the parts are.
But all that is neither here nor there. The point is that in an 80 character line, which may well be indented 16 characters, underscores can occupy 10 characters.
0
Jan 05 '11
Again, you seem not to have understood the point.
Again?
The point is that using underscores can add significantly to the length of a line, over using camel case.
I didn't comment on that.
As to the things you say about the code
That is the actual things I say.
in the first place it was an off the top of my head example, not an excerpt
So you don't normally use 'instance' suffix?
the second place, the code I had been working on earlier actually has two lists of names, so I need to distinguish between author_names and package_names.
I did acknowledge that.
I make the parts very explicit, anticipating that I may have to look at it weeks from not when another bug gets noticed and I remember less what the parts are.
That's fair but I'm not sure on how obfuscating your variables is helping that.
But all that is neither here nor there. The point is that in an 80 character line, which may well be indented 16 characters, underscores can occupy 10 characters.
That's hardly the case if you are not in habit of making your variables unnecessary long. I'd argue that if you're ever near 80 chars line limit then you must be doing something wrong.
Still, this is not what I was commenting on before.
0
1
u/pdc Jan 02 '11
I use variable-width fonts in text editors by preference, in which case swapping capital letters for underscores makes less of a difference in line length.
Also I observe that young people seem to like to run their text editors full-screen, which gives them over 160 characters to cram a line in to. A few extra underscores will make little odds in this case!
1
1
Jan 02 '11
Swap underscore with dash, if you're writing in PEP 8 style you probably use it a lot more, and hitting shift for occasional dashes in human text is not as troublesome or common.
1
u/_pep_8_ Jan 02 '11
Am I missing something here? Dash is not allowed? In any case, both are on the top row.
Read the testimonials of people who have shifted to a Dvorak layout (for regular English, not programming). The don't necessarily gain a huge speed advantage but most of them do rave about how they don't get RSI type feelings anymore. That's because the Dvorak is designed to limit as much finger movement as possible by putting the most commonly used letters on the home row. The small, if not insignificant gain in readability just isn't worth the reach over and over.
2
1
Jan 02 '11
We should be extremely happy that something like PEP 8 exists. It's not about good style, bad style, personaly preferences. I like this, I like that...
Some of you guys may have been involved in creating a standard or convention. That's a never ending nightmare, because everyone fights about mainly personal preferences. However, the point is to have the convention. Whoever wrote PEP 8: Thank you, thank you, thank you!
I had to get used to the underscores coming from CamelCase myself. I still have quite often problems with line length as my names get quite long.
1
u/_pep_8_ Jan 02 '11
I'm happy PEP 8 exists. Just wish it was internally consistent and consistent with Java. Its inconsistent in the sense CamelCase for classes and underscores for methods\variables. If it just stuck with mixedCase for the latter it would have been internally consistent and consistent with some of the most widely used languages out there.
A lot of people forming full sentences in CamelCase are confident that that it is much harder to read than underscores, but they don't do it with much short identifier names because that shows its really not that bad. Plus, a Java or C# or Javascript programmer coming over and trying out Python is going to be more comfortable with the mixedCase than underscores. Adding in the removal of { and ; everywhere Python is a very clean looking language.
1
Jan 04 '11
Yeah, I also think CamelCase is not so bad. Also, I agree that it would be great if there was a language embracing convention. I wouldn't care too much what it would be like.
But that's only a distant dream :-). For now I think the best we can do is be consistent with the environment as mitsuhiko (tough name to type and read, mit_su_hiko would be easier ;-)) suggests.
2
u/mitsuhiko Flask Creator Jan 02 '11
In C# I NameMyFunctionsLikeThat, inJavaLikeThat, in_python_like_that, in_c_like_that, in_cpp_like_that, In_Ada_Like_That. I don't have a problem with either, but I stay consistent with the environment I am working in.
0
u/tesseracter Jan 02 '11
can't downvote you, but i dislike the cut of your jib. my idea of good looking python code is not being able to tell a 99 bottles of beer script from a neural network on the shape of the code alone -- it all looks neat, clean, and plain. leave all the complicated stuff to ruby/perl folks who think they are 'code ninjas/rockstars' and allow me to go in and use your python code in a super boring and productive matter. this means following pep, and therefore getting the magical ability to guess function names without looking at your source code, and having it be intuitive enough to just get it right.
1
u/_pep_8_ Jan 02 '11 edited Jan 02 '11
I'm not sure you are addressing me directly or maybe you meant to reply to someone else commenting here? This code ninjas/rockstars comment seems far out in left field to me.
I agree with almost 99% of what the PEP says. I try my best to follow it. I dislike the recommendation to move forward with underscores and the mix of choices I like I'm seeing in the threading module inspired by Java. Personally, I think the PEP should have stated something to the effect, that when using all lowercase makes a long, unreadable name either use an _ to separate parts of this name or capitalize the words within it like Java.
People declaring there is some huge problem with readability with mixedCase and that underscores are superior and maybe happy the PEP suggest this are probably missing the fact that Python follows the Java CamelCase convention for naming classes.
The PEP makes this statement
Capitalized_Words_With_Underscores (ugly!)
yet I don't see a huge difference between that and this: capitalized_words_with_underscores.
If Java was written with underscores all over the place we could probably complain it looked more convoluted and verbose than it already does. Because the underscores create noise and extra whitespace where whitespace is significant and distracting when looking at a program.
2
u/tesseracter Jan 02 '11
python actually uses TitleCase, not camelCase. small difference, but one looks better than the other.
the rockstar comment was just because i hate working with folks that think their personal style is the awesomest, and trumps convention.
1
u/_pep_8_ Jan 02 '11
No, I got it wrong. Check the PEP. It explicitly declares CamelCase the same as CapitalizedWords. It calls what I called camelCase, mixedCase.
0
u/draconian Jan 02 '11
I much prefer camelCase to using_underscore myself.
42
u/namcor Jan 02 '11
CamelCaseGetsAnnoyingWhenYouStartCombiningManyWordsTogether
using_under_score_is_much_more_readable_which_is_why_PEP8_recommends_it
AlsoCamelCaseDoesNotWorkWellWITHUPPERCASEDTHINGS
whereas_UNDERSCORE_does
2
u/_pep_8_ Jan 02 '11
Namcor,
Thanks for the input. I think your examples are illustrative, but they are too extreme. So they distort the true differences here to make the case that the underscore is vastly more readable. Do you really name your identifiers like this? I think these are sentences, not identifiers and thus in the context of reading a sentence the extra white space created by the underscore helps. What about here?
# example number 1 if my_long_variable_name > 0: print("greater than 0")vs
# example number 2 if myLongVariableName > 0: print("greater than 0")There is another recommendation in the PEP which suggests you cut down on the spaces between lines. A blank line is to help allow the eye to see something significant. The whole concept of the enforced white space to indent is also making white space something significant. White space is telling me something about the overall context of where I am at in my program. My point with all this is, that in the first example above, the white space and separation created by the underscore, in the interest of "readability" is going too far, its chopping up the line too much. Instead of four of five symbols I'm now parsing out eight because the underscores are creating extra white space gaps. I want to see an identifier as a single thing not four things in this case. And this is just one line of code, this difference adds up quickly.
Now you may not buy this explanation and that is fine, but I think there is a cost there and this emphasis on separation between words in an identifier comes at the cost of making the whole statement harder to grok. The statement is more than its identifier and white space is important to seeing that statement.
I think in some ways you and I are in the same boat. You are expressing a dislike for the CamelCase, yet the PEP tells you that you have to use CamelCase. And that very same PEP cites an example that ironically enough, goes against your concerns over capitalization
Quote:
Note: When using abbreviations in CapWords, capitalize all the letters of the abbreviation. Thus HTTPServerError is better than HttpServerError.
CapitalWords, CamelCase (I meant to say mixedCase before) is the requirement for naming classes. So the odd thing about the overall readability argument that is made about underscores is that the PEP itself is inconsistent in these matters. You may think HTTP_Server_Error is much more readable but the PEP actually literally declares this mixed case, underscore naming convention as "ugly!".
2
u/pdc Jan 02 '11
Annoyingly upper-case abbreviations in camel case is the opposite convention from the Microsoft (C# et al.) world, where you would use
XmlHttpRequestrather thanXMLHTTPRequest.1
u/_pep_8_ Jan 02 '11
Per PEP 8, you have to use XMLHTTPRequest if that is a class name. Microsoft's is definitely more readable in my opinion, but its not a huge deal. Its only 14 characters and it doesn't take long to grok it as one thing as opposed to the underscore folks who think it would be better having to break it apart into 3 things each time they see it and then reassemble that out with the rest of the whitespace in their statement.
In the interest of making something that should just be perceived as one unit or chunk more "readable" they are making the rest of the surrounding context of the program harder to grok.
4
1
u/eriiccc Jan 02 '11
My work is in Perl, and we're in the process of transitioning to Python.
The camelCase vs. underscores was one of the few things that bothered me ( along with the 79 char/line thing).
This was the best justification for the underscores. Thank you.
4
u/pingveno pinch of this, pinch of that Jan 02 '11
79 or fewer characters per line is very nice when viewing two files side by side. Even a wide screen monitor can't comfortably view two files with very long lines.
1
u/eriiccc Jan 02 '11
The 79 char thing is part of our Perl guidelines too. We have a 79 char soft limit with a 100 character hard limit.
I wanted to see it carry over to our python guidelines, but it didn't.
1
u/tesseracter Jan 02 '11
i break the 79 chars all the time, but not by much. if its a list, it should be one per row, if its a function, it probably shouldn't have much more than 3 levels of indentation, so split things up a bit more.
comments and super sweet one-liner list-comprehensions are my big offenders.
1
0
Jan 01 '11
[deleted]
11
u/kanak Jan 01 '11
For personal projects, do whatever you feel like. But if you intend on getting contributions, having a non idiosyncratic coding style will ease the burden on contributors.
-3
u/acct_rdt Jan 02 '11
Nobody who can grasp software development would be so stupid as to struggle with a certain type of indentation or variable naming that they're not used to. Calling this a burden in the context of the type of problems that developers have to solve all the time is silly.
Your only obligation is to make your code consistent with a reasonable style, not adopt someone else's arbitrary style decisions.
4
u/tesseracter Jan 02 '11
which is one reason i HATE using twisted. you're a python library that you expect other people to use. don't make me learn all your silly method names like ruby/perl, i want to be able to guess a method and get it right once in a while.
you're not being smart and new, you're slowing everyone down.
0
u/hylje Jan 02 '11
Programming is at its core about grasping as many details and solving the problem with the details turning out ideally.
Burdening the programmer with non-obvious style and naming will reduce the capacity available for considering details. Less details, worse code.
1
u/_pep_8_ Jan 02 '11
Burdening the programmer with non-obvious style and naming will reduce the capacity available for considering details.
But we aren't discussing a non-obvious style. We are discussing convention that doesn't use underscores, CamelCase and mixedCase. The most popular language on the planet that has inspired various python standard library modules uses this convention. A language most people are forced to use if they do any web programming, Javascript and its popular 3rd party libraries use it.
Python and the PEP itself actually recommends part of this non underscored convention for its class names. There is nothing that difficult or hard about reading CamelCase until people start making full English sentences out of it like they do here.
1
u/hylje Jan 02 '11
Grandparent is talking about mixing multiple styles for lulz. Mixing multiple styles in the same context makes style non-obvious and a thing to consider when writing code.
3
u/DasIch Jan 02 '11
The point of PEP 8 is not to enlighten the world with the authors aesthetic idea of coding style and to provide the style which looks best, even though this is certainly attempted.
The point is that everyone follows the same conventions in order to provide consistency among all python projects, which in turn prevents you from having to memorize the style guides of every project and dependency those projects might have because this truly has to be how the hell of coding styles looks like.
No matter what your views on specific rules introduced by PEP 8 are, I surely hope you strive for consistency and can at least appreciate that.
0
Jan 02 '11
If you expect anyone in the world to read your code, or if you expect yourself reading somebody else's code, then you should stick to conventions. It makes your life also easier. Actually, if I would need to hire a Python programmer and see in his code examples that he does not follow PEP 8, I would not hire him.
11
u/mcilrain Jan 02 '11
usingCamelCaseIsARealPainToReadItIsAlsoAProblemWhenDealingWithAbbreviationsYouMaySayHTTPButSomeoneElseMightSayHttp
underscores_are_much_nicer_in_this_regard_http_will_always_be_http
Python is supposed to be a language that's easy to read by humans.
Personally, while looking for a library I will often pass any that don't follow PEP 8. (You wouldn't hire someone whose resume is in leetspeak, now would you?)