9 ms·
Python: Myths about Indentation
- LeafStorm 15y agoOne nice thing about significant indentation is that it forces new programmers to learn how to indent their code properly. I'm taking an Intro to Java course now (in retrospect, I should have tried to place out), and most of the students in the class have absolutely terrible indentation. The only major downside of significant indentation is that it makes it impossible to define multi-line anonymous functions in a clean way.
- Jach 15y agoI totally agree with you on indentation. I started with PHP and didn't bother indenting at all for a long time, then when I did it was only a single space. I tried three spaces for a while in an AP CS course in high school (I also tried and hated Python for a weekend during that first semester), then toward the end of that year I learned Python more seriously and fell in love. I still only indent two spaces though, my One True Way. =P I think part of my initial dislike for Python was manually typing nested indentation, even with one space the level for class->def->for->if can get annoying to type. I used to use EditPad Lite that didn't have auto-indent. Everything got better once I learned vim. Regarding multi-line lambdas in Python, you can do it more or less but like you said it's not clean and can be dangerous. a = [1] blah = lambda x: eval(compile(''' print x a.append(x) ''', '', 'exec'))
- anamax 15y agoPython's lambdas aren't functions, they're single expressions, so I don't think that the multi-line problem is significant. I'm not convinced that multi-statement anonymous functions are a good idea.
- rogerdpack 15y agoThey can make for pretty statements in Ruby. But my question is then...why can't you do it in python just like ruby def go : this.some_other_method : here_is_my_block ?
- gbog 15y ago> multi-line anonymous functions This is maybe a bit far from the topic, but I would like to know why there is such a need for anonymous functions in Python. I understand very well the need for stateless functions (functions that do not change anything else than their return value, have no side effect, except maybe logging), and I understood it was a piece of functional programming. In Javascript, with silent overwriting of functions and without modules, it is obviously very bad to pollute the only namespace with function names that can clash with each other, but in Python, you are or should be always inside a relatively small scope, and there you can def _my_temp_func() without any problems, no? Moreover, as it is lame to use _temp as function name, it forces you to formulate a meaningful function name, which is good pratice, especially for your lectorate, right? Or am I missing something?
- burgerbrain 15y agoI don't know python, so I don't know if anonymous functions have been crippled there, but in other languages anonymous functions are used to do things such as create closures (not stateless). For example, in scheme: > (define (foo x) (lambda (y) (+ x y))) > (define bar (foo 10)) > (bar 5) 15 This sort of thing is of course immensely useful.
- andrewaylett 15y agoYou can do the same in Python, with named functions or lambdas: >>> def foo(x): ... def add(y): ... return x + y ... return add ... >>> bar = foo(10) >>> bar(5) 15
- masklinn 15y agoAnd it takes twice the token count and lowered readability for no gain whatsoever.
- burgerbrain 15y agoNo gain at all? How do you figure?
- parfe 15y agoPython white space indentations adds some overhead when pasting code but overall I feel improves the code I write and the code I have to read. I think if it were possible to do multiline anonymous functions a lot of the feel of python would change and there would be a lot more function calling with nested anonymous blocks. I don't know if that would be an improvement or not, but I personally like my coworkers (and me) being forced to have a binding to the code they are writing in the block they are writing it in. The adverse visceral reaction to white space (which I think is akin to the reaction to parens in lisp) appears to me to be people being unhappy with being "forced" to do something. These (for me) happen to be the same people who don't understand why the code they wrote in their personal (and ever fluid) style is no good to be added to our code base.
- berntb 15y agoInteresting. Do you have references to support that code blocks are bad? They are popular most everywhere else? (-: It sounds like a cripple claiming they don't need their missing body part. :-) The last paragraph is a straw man imho -- people have no business having a programming job if they can't use their team's code formatting rules. (If they work in a team of one, they still need to specify and follow coding/documentation standards.)
- parfe 15y ago>Do you have references to support that code blocks are bad? Which part of my post gave you the impression I was talking about anything other than direct personal experience? I made sure to be explicit about it. I even say I don't know if they would be good or bad, but gave a reason why I like python disallowing them. edit: I take exception to the idea that my personal opinion needs to have a "reference" which would boil down to the personal opinion of another random person on the internet who supports my position authoring a blog post that looks "sciencey". Opinions on language features does not produce scientific studies.
- berntb 15y ago>>I take exception to the idea that my personal opinion needs to have a "reference" Oh, private musings instead of an argument? Less interesting. :-)
- vessenes 15y agoPython's indentation rules as specced originally are considered too loose by most Python programmers, hence PEP8 -- specifying spaces only, and a host of readability rules. Consider that the competing scripting language at launch was Perl. Now consider the benefit to a large team of well formatted easy to read code; Python's whitespace and indentation rules are there to enhance maintanability and readability, and they generally work. As the article shows, you CAN make python look worse, but you shouldn't. Incidentally, languages like Google Go take this one farther and embed deterministic formatting as a part of the language toolkit. This is brilliant. I would like to see such a thing incorporated into Python as well.. (Where's my backlist of to-do items?)
- mcantor 15y agoThis is the main point: "So the conclusion is: Python forces you to use indentation that you would have used anyway, unless you wanted to obfuscate the structure of the program." You were going to use consistent indentation anyway, right?
- onedognight 15y ago> "You cannot safely mix tabs and spaces in Python." You can mix spaces and tabs all you want as long as you are consistent. This is fine. if 0: <tab><sp><tab><sp>1 <tab><sp><tab><sp>2 This is not, for any number of spaces. if 0: <tab>1 <sp><sp><sp><sp><sp><sp><sp><sp>2
- falcolas 15y agoTechnically, the parser converts one tab to 8 spaces (at least in the versions of python I'm familiar with), so your second statement is not quite true. def foo(): <tab>print 'a' <sp><sp><sp><sp><sp><sp><sp><sp>print 'b' compiles and runs properly in python 2.6.
- chaostheory 15y agoQuestion: why don't pythonistas use tabs instead of spaces for indentation? To my knowledge pretty much every editor can be customized to display tabs in whatever length users want e.g. 2 spaces, 4 spaces, etc... imo it's a lot easier than dealing with different sets of code with a varying number of spaces for indentation.
- veyron 15y agotabs are interpreted as exactly 8 spaces, and oftentimes people set editors to use less than 8 spaces
- nhaehnle 15y agoWhy is that a problem though? If you consistently always use tabs for indentation, this interpretation does not matter.
- burgerbrain 15y agoWhy does it matter to you if people set their editors that way? What is your point here?
- veyron 15y agoSome people write assuming that 8 spaces and tabs are interchangeable. I can change my habits but cant change others. And in those cases, I have to set my tab width to 8 spaces to read it properly. I'm not condoning it -- but you have to realize that oftentimes we have to interact with others' code
- ominous_prime 15y agoThe standard indentation is 4 spaces, and people often have their tabwidth set to 4 spaces. Sometimes tabbed code (often older code, before spaces were really standard), end up with mixed tabs and spaces. The logic of the code then reads completely differently depending on your editor settings.
- 15y ago
- veyron 15y agoMyth: "You cannot safely mix tabs and spaces in Python." In fact, you can mix 8 tabs with spaces in CPython (and do wacky stuff like def f(): <tab><8 spaces>x=3 <4 spaces><tab><4 spaces>y=3 <8 spaces><tab>return x+y
- andrewaylett 15y agoYou can, yes, but is it safe? My understanding of the article is that you shouldn't do it, because it's liable to cause confusion -- it's not safe.
- koenigdavidmj 15y agoIn Python 2, you can run tabnanny[1]. In Python 3, I do not believe that unambiguous tab mixing is allowed. 1: http://docs.python.org/library/tabnanny.html http://docs.python.org/library/tabnanny.html
- phzbOx 15y agoI'm an avid python user and a big problem I have is that you can't finish a line with '.' and continue on the next line. For instance: some_object. do_something(..). do_something_else(..). Doesn't work. It needs to be written: some_object.\ do_something().\ do_something_else() or some_object\ .do_something()\ .do_something_else() It's ok to write \ a couple of time, but I feel like it makes chain-able functional methods really ugly to use because of that.
- pyre 15y agoYou don't need to escape line endings within parens: (someobject .do_something() .do_something())
- phzbOx 15y agoYeah. That's the hack I use, but it makes it a bit no pythonic.
- pyre 15y agoFrom what I gather, the Pythonic way to write that would be: some_object.do_something().do_something()\ .do_something().last_thing() Basically, go to the end of the line and wrap with an indent. That's the way that I see most function calls with a long list of arguments in Python. In Perl, you might see something like: GetOptions( 'h|help' => \my $help ); Whereas in Python you would see: parser.add_option('-h','--help',meta="HELP",target="HELP", help="Print help message",action="store_true",default=False)
- Thrymr 15y agoIt seems to me all the resistance from people who don't like Python's meaningful indentation is from people who haven't coded in Python. It seemed weird to me at first, too, but really, it takes about an hour of actually using code to think, "Hey, this just lets me get rid of all the ugly brackets, and you don't lose anything by having to write it this way!" I don't even think you have to love Python as a whole to get the fact that this part of it is simple and elegant.
- njharman 15y agoI can attest to this being one of the people who resisted until I actually used the language. Now I absolutely can't stand languages without significant indentation. "why is this retarded language forcing me to manually end blocks when it's bloody obvious from indentation!!!"
- jarin 15y agoI don't really have a problem with Python per se, but the one thing that bugs me is that the significance of indentation encourages the use of 4 or 8 space indents. I guess on one hand it's good because it would probably discourage heavy nesting, but seems like it would be a pain to paste on blogs and would require a lot more eye movement. I guess you probably just get used to it, I'm just coming from the 2 space Ruby standard.
- jpr 15y agotl;dr def foo(x): ... stuff ... ... more stuff ... should be synonymous with foo = lambda(x): ... stuff ... ... more stuff ... but isn't, because guidos think that they know better.
- pyre 15y agoI will say that the person I know with the most visceral reaction to Python's indentation rules writes code like this: sub func { shift->func1(shift)->func2(@_) } sub things_with_attr { grep { $_[0]->is_attr_true($_) } $_[0]->things } Only the function names have been obscured.