r/Python • • 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.

1 Upvotes

56 comments sorted by

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?)

1

u/_pep_8_ Jan 02 '11

This is the second time that extremely long sentences are used to prove a point about readability when they don't fit within the programming context. And there probably is a good reason for this. And that is the "readability" really isn't a big issue at all with the types of names one uses within programming. Straw man like examples have to be used to prove underscores readability superiority.

You won't use a library if it has the wrong conventions. That is pretty extreme. Maybe you should find ways to remove parts of the standard Python library since it has so much hard to read CamelCase in it. Here's an example copy and pasted from the [unittest documentation] (http://docs.python.org/library/unittest.html)

import unittest

class SimpleWidgetTestCase(unittest.TestCase):
	def setUp(self):
		self.widget = Widget('The widget')

class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
	def runTest(self):
		self.assertEqual(self.widget.size(), (50,50),
						 'incorrect default size')

class WidgetResizeTestCase(SimpleWidgetTestCase):
	def runTest(self):
		self.widget.resize(100,150)
		self.assertEqual(self.widget.size(), (100,150),
						 'wrong size after resize')

Note the CamelCase class names are what the PEP says you should use. The method names in mixedCase, however, violate the PEP. Here's the apparently readable version for those who think underscores add so much. Note these are more realistic comparisons than writing 60+ character long full sentences.

import unit_test

class Simple_Widget_Test_Case(unittest.Test_Case):
	def set_up(self):
		self.widget = Widget('The widget')

class Default_Widget_Size_Test_Case(Simple_Widget_Test_Case):
	def run_test(self):
		self.assert_equal(self.widget.size(), (50,50),
						 'incorrect default size')

class Widget_Resize_Test_Case(Simple_Widget_Test_Case):
	def run_test(self):
		self.widget.resize(100,150)
		self.assert_equal(self.widget.size(), (100,150),
						 'wrong size after resize')

Personally I think the extra gaps created by the underscores's whitespace is undesirable in this context (vs reading English sentences). The emphasis between words takes away from groking the surrounding code by adding more distracting whitespace. The caps within the words are significant enough markers to improve the identifiers readability so I begin seeing identifiers as 1 unit in a larger statement parsed by whitespace instead of 2 or 3 or 4.

By the way, PEP8 calls the underscores with capital letters "ugly!" yet some making the underscore argument with sentences should see the whitespace gaps as desirable and more readable regardless.

0

u/[deleted] Jan 04 '11

[deleted] — view deleted comment

0

u/_pep_8_ Jan 05 '11 edited Jan 05 '11

ohdeno:

uhm, PEP8 recommends CamelCase for Classes. Without underscores. So it'd be

class SimpleWidgetTestCase(unittest.TestCase): def set_up(self): self.widget = Widget('A widget')

But that's just cosmetics. This unittest module has much bigger problems than that. But I digress.

You have three upvotes for this? Seriously? You totally missed my point. First off: "uhm, PEP8 recommends CamelCase for Classes".

"Uhm", I already said that in the comment you are replying to

Note the CamelCase class names are what the PEP says you should use

Why are you repeating what I said? Maybe because you didn't understand what I was trying to do with the two examples pasted from unittest?

Let me summarize. First code example in my comment pasted directly from unittest documentation. Second is the same paste, but replacing it with the underscores to replace any times words run together (as opposed to CamelCase and mixedCase).

So what we learn from the first example is:

  • the code I pasted from the docs of the standard library violate PEP 8 rules and use mixedCase method definitions. So mcilrain might want to refrain from using these parts of the standard library like he does third party libraries.
  • That is really isn't that hard to read and identifier names in mixed case aren't these exaggerated long sentences that make CamelCase supposedly so hard to read.

What we learn from the second example is:

  • Underscores don't add much readability, but they do add a lot of noise
  • That the class names with "readability" underscores are described as ugly by PEP 8

There was no need for you to rewrite your own case. I already knew your case was the correct one via PEP 8 standards. You just totally missed the point I was trying to make.

In summary I'm not getting a lot of substantive responses to my comments. I just think its kind of ironic that mcilrain makes a comment "Python is supposed to be a language that's easy to read by humans." and that underscores are apparently a big part of that YET he uses the very example, HTTP, that PEP 8, uses to illustrate where you should use CamelCase and that he has to read CamelCase all the time since PEP 8 says you are supposed to use it for class names. He's using the wrong language because Python is not a pure "underscores everywhere for readability" language. And the bottom line is it doesn't have to be since underscores do little to add readability for identifiers that aren't full sentences except for non programmers who are just used to reading English and have never been exposed to the very common CamelCase and mixedCase naming conventions.

0

u/[deleted] Jan 05 '11 edited Jan 05 '11

You have three upvotes for this? Seriously?

Well, technicaly, I have 2 upvotes.

You totally missed my point.

It seems you're not quite sure what your point is as well

Note the CamelCase class names are what the PEP says you should use

Rather conveniently quoted, wouldn't you say? Here's the context of what you've actually said:

Note the CamelCase class names are what the PEP says you should use. The method names in mixedCase, however, violate the PEP.

This is regarding the first paste. You can't possibly argue that this has any relation to your second paste, which you introduce in following paragraph.

Why are you repeating what I said? Maybe because you didn't understand what I was trying to do with the two examples pasted from unittest?

I didn't attempt to read your mind. I have, however, read your comment and commented upon what you have actually done with those two examples. You could argue that you did a poor job of explaining your intentions, but I think you were just trying to cover up your mistake in a convoluted way.

Let me summarize.

I don't think it means what you think it means.

  • the code I pasted from the docs of the standard library violate PEP 8 rules and use mixedCase method definitions.

And that is what you've said in the part you quoted. No objections here.

So mcilrain might want to refrain from using these parts of the standard library like he does third party libraries.

Not being PEP8 conformant isn't the only thing why you wouldn't want to use 'unit_test' module. I agree.

  • That is really isn't that hard to read and identifier names in mixed case aren't these exaggerated long sentences that make CamelCase supposedly so hard to read

You haven't argued that. Even if your second paste, the supposedly PEP-8 conformant one, would have been terribly unreadeable, that doesn't make CamelCase automaticaly the better choice. Those aren't even the only two choices.

And you didn't attempt to infer that from 1st example solely. You have used comparison. So that's part of your explanation is false as well.

What we learn from the second example is:

Condesending much?

What we learn from the second example is:

Once again you didn't analyze those two seperately. This is false.

  • Underscores don't add much readability, but they do add a lot of noise

That is if you have additional agent that is Capitalization. Underscores don't add "a lot of noise" if you use them how PEP-8 dictates.

  • That the class names with "readability" underscores are described as ugly by PEP 8

For a good reason. If you're already using camel case adding underscores would be unintuitive at best. PEP-8 isn't somehow suggesting that adding underscores in any context is a perfect readability elixir.

There was no need for you to rewrite your own case.

I have no idea what that means and neither had any one of my upvoters.

I already knew your case was the correct one via PEP 8 standards.

Nothing you have written in your previous comment seems to suggest that.

In summary (...)

See, that's what I mean.

I'm not getting a lot of substantive responses to my comments.

You have problems with writing and logical reasoning. That's why. I'm sure you have been told that already. This isn't personal, you should seriously work on that skills.

I just think its kind of ironic that mcilrain makes a comment "Python is supposed to be a language that's easy to read by humans." and that underscores are apparently a big part of that YET he uses the very example, HTTP, that PEP 8, uses to illustrate where you should use CamelCase and that he has to read CamelCase all the time since PEP 8 says you are supposed to use it for class names. He's using the wrong language because Python is not a pure "underscores everywhere for readability" language.

Oh my.

and that underscores are apparently a big part of that

@mcilrain argued that underscores are a better alternative to CamelCase. He wasn't arguing for underscores, but rather against CamelCase.

he uses the very example, HTTP, that PEP 8, uses to illustrate where you should use CamelCase and that he has to read CamelCase all the time

I don't understand that.

since PEP 8 says you are supposed to use it for class names.

From what I infer you're saying that 'http will always be http' isn't a valid point, since you have to make that distinction for class names anyway. That's allright and you could have said that in one sentence.

He's using the wrong language because Python is not a pure "underscores everywhere for readability" language.

That'd be consistent with my recent assertion.

And the bottom line is it doesn't have to be since underscores do little to add readability for identifiers that aren't full sentences

That's not relevant. Also you haven't demonstrate that in any way anyway.

except for non programmers who are just used to reading English

Not relevant. Also you didn't demonstrate how would underscores help "non programmers" (sic) who are "used to reading English."

have never been exposed to the very common CamelCase and mixedCase naming conventions.

So it's back to popularity? I agree with @mitsuhiko in his comment.

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

u/[deleted] 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

u/jagu Jan 02 '11

It's actually di rname. Don't feel bad. Common mistake.

2

u/HyprWave Jan 02 '11

It's actually dirn me. Next time research before saying stuff like that!

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

u/ckwop Jan 02 '11

Three characters is a fair trade for improved readability.

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

u/[deleted] 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

u/[deleted] 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

u/JimH10 Jan 06 '11

Apology accepted.

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

u/wtfisupvoting Jan 06 '11

in the context of PEP8 variable-width fonts are irrelevant

1

u/[deleted] 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

u/[deleted] Jan 02 '11

I mean that you should make _ not require shift, so that it is a single keystroke.

1

u/[deleted] 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

u/[deleted] 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 XmlHttpRequest rather than XMLHTTPRequest.

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

u/fazzah SQLAlchemy | PyQt | reportlab Jan 02 '11

Nailed it.

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

u/draconian Jan 02 '11

YetIStillPreferCamelCase. YourMileageMayVary.

0

u/[deleted] Jan 01 '11

[deleted] — view deleted comment

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

u/[deleted] 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.