10 ms·
C++ Has Become More Pythonic (2014)
- wglb 11y agoProps to python. However, what idea has C++ not accepted? It seems for it to be a "new" language, it should at least say "no" to something.
- smcameron 11y agoC++ says "no" to readability. Everything that has been added to C to create C++ was added in order to help out the person writing new code. Nothing that was added to C to make C++ is there to help the person trying to read the code. Though I doubt it was deliberate, much of what makes C++ different than C seems actively hostile to the person trying to read the code.
- jordigh 11y agoYou really find auto x = new int[64]; harder to read than int* x = malloc(sizeof(int)*64); ? If so, I think it's just a matter of habituation and imprinting. Whatever you learned first is easier and everything else is hard.
- smitherfield 11y agoBoth C and C++ have readability issues. ((void(*)())exec)(); or template <typename T> struct value_type { typedef typename T::value_type type; }; template <typename T> struct value_type<T*> { typedef T type; }; Six of one, half a dozen of the other.
- emmelaich 11y agoI think there's a gap that could be filled by making a nice front-end to C++ with nicer simpler (even Pythonic) syntax. Drop the semi-colons, convert "dict of int to string' to map<int, std:string> etc. It would be ok if it only did a subset of C++ at first.
- dmytrish 11y agoSounds like http://nim-lang.org/ http://nim-lang.org/ . Just simplifying syntax is not a great idea for a system programming language though.
- Tyr42 11y agoIt doesn't have yield. It also doesn't have Concepts yet, as they got pushed back again.
- marvy 11y agoThey're working on Concepts, and they're working on yield (search for resumable functions). Maybe they can say "no" to "saying no"? :)
- twiceaday 11y agoI'm still waiting on Pythonic iterators (e.g. coroutines).
- cheez 11y agohttp://www.boost.org/doc/libs/1_60_0/libs/coroutine2/doc/html/coroutine2/coroutine/asymmetric.html http://www.boost.org/doc/libs/1_60_0/libs/coroutine2/doc/htm...
- discardorama 11y agoI'm sure I'm not the only one who doesn't like how these things are bolted on and shoehorned into the existing constructs, resulting in some ugly-ass syntax. Consider: auto triple = std::make_tuple(5, 6, 7); std::cout << std::get<0>(triple); Ugh. And don't even get me started on "myList.push_back(5)" . "push" usually means "add to the front"; why not use "append" ?
- leetrout 11y agoSigh - I know why you got downvoted but I came to post the same thing. I don't program in C++ but specifically the std::get<0>(triple) It really doesn't look great. It looks like the template syntax using the <>. I'm sure I would get used to it if I were using it every day but from an aesthetic sense it doesn't win me over.
- SamReidHughes 11y agoIt is the template syntax.
- SamReidHughes 11y agoIn Perl, "push" means "add to the back."
- fndrplayer13 11y agoAs a developer who used to build systems in embedded C++ and now spends all of my time building web backends in mostly Python, I have to agree with the premise that C++ is becoming more influenced by Python. That's a good thing, I think. I really think C++ is a wonderful language if properly curated and used by a responsible team of developers. One tiny thing that would be cool to see built into C++ would be an equivalent to the Python range function. The boost version is nice for now, though. Finally, I also see this as a nice compliment to Python and the power that it offers as a language.
- eplanit 11y ago"As a developer who used to build systems in embedded C++ and now spends all of my time building web backends" I'm curious, what motivated your switch from embedded to web?
- fndrplayer13 11y agoI loved being an embedded developer. Loved it. I had been out of college for 4 years and thought that the work at startups would be even more exciting. I took a job as a backend developer at my current company because I was really excited about the technology they were working on from a conceptual level, and I still am. I transitioned from working on computer vision/image processing embedded work to natural language generation stuff in AWS. The AI aspect just generally excited me, but so did expanding my skill set in a much wider sense. Today I can talk about embedded concepts all the way up to AWS concepts like lambdas, cloud formation, etc. That's a pretty cool breadth of skill (notice I didn't necessarily say depth :P). I still feel like an embedded developer at heart, though. I'll go back to it someday.
- eplanit 11y agoThank you, interesting. I am curious because I've gone the other direction. I began in the latter 1980s on the IBM PC (literally with IBM). At IBM they gave us a PC, a copy of the Technical Reference Manuals, and a screwdriver. It was really fun to learn the machine literally from the metal upwards. Beyond the screwdriver was Macro Assembler and a C compiler. Avoiding reminiscence, the point is that over the ensuing years my career took me further and further up the stack into software only, from end-user applications to a long time in the server "backend" space. During those years I became ever decreasingly aware of the hardware and internals of the OS. Machines themselves became "virtual instances". Thus is the modern world of highly scalable, distributed 'net and [dread] enterprise computing, and it's all great and exciting in many ways -- but, for me I also felt that my heart was happiest when thinking of things at the lower level. That drove playing with embedded systems, which led ultimately to a complete career shift. All is good. And, yes, we are all so very fortunate to be in an economic segment (technology, hardware and software) that allows us such freedom to choose our paths (and then change them).
- nv-vn 11y agoNone of these ideas seem outright specific to Python and I don't think it makes sense to attribute all these changes to Python influence. C# and D, for example, have had most of these features for a few years. One could just as easily say "how C++ is becoming Haskell" or "how C++ is becoming Go" (both of which have many of these features). I think a better title for this would be something along the lines of "Python idioms in C++".
- coldtea 11y ago>how C++ is becoming Go Hmm? Go has almost none of these features.
- nv-vn 11y agoIt has tuples, local type inference, for loops on ranges, and anonymous functions/lambdas (which act as closures/"capture" scope). Hardly "almost none of these features".
- leetrout 11y agoI'm new to Go- but I don't think it has tuples in the python sense[1]. Happy to be corrected here if there's a broader definition you're referring to. I do wish it had support for slice unpacking like it does for return values. The assignment from returns or ranges is one of the things I really ejoy. Edit: [1] I'll clarify that I define that as an immutable, indexable data structure that you can unpack in to multiple assignments.
- nv-vn 11y agoIt doesn't have "true tuples" but you can do multiple returns in a tuple-like way and there is syntax for unpacking it. While a pair can't be stored in a single variable, you can just manually unpack and repack them for a similar effect to what tuples can do. For the record, most languages don't have indexable tuples as far as I'm aware and make you unpack them with some form of pattern matching.
- ioab 11y agothose are amazing features I didn't expect C++ to have. I wonder if 'auto' is similar to type inference 'var' in C#.
- catnaroek 11y agoC# does not have type inference: http://ideone.com/fmm92M http://ideone.com/fmm92M. Nor does C++ for that matter: http://ideone.com/HzyM2E http://ideone.com/HzyM2E. This is type inference: http://ideone.com/0Gv8fV http://ideone.com/0Gv8fV, http://ideone.com/r9nHUF http://ideone.com/r9nHUF. Note how the type checker figures out the list's element type from how the list is used.
- deleted 11y ago[deleted]
- SamReidHughes 11y agoNote how that's an anti-feature.
- catnaroek 11y agoWhether a feature is a good or a bad thing to have is each programmer's subjective opinion. (But, of course, mine is diametrically opposed to yours: typeful programming would simply be impractical if you had to babysit the type-checker all the time.) OTOH, whether a language has or doesn't have a feature, is a technical fact.
- SamReidHughes 11y agoIt's not subjective at all. Features are good or bad for productivity. Maybe you have a different goal or have calculated the expected value differently, but with a well defined purpose it's not a subjective question.
- pcwalton 11y ago
- massysett 11y agoauto is type inference. That's not "pythonic", that's something that statically typed languages have had for decades. Indeed, it's nothing like Python, where general practice is to pass around things derived from Object and depend on runtime typing failures. There's also nothing Pythonic about lambdas. Come on, lisp is ancient and it has lambdas. This article essentially says C++ got stuff that has been around for decades, and Python has stuff that vaguely resembles them, so C++ is learning from Python.
- catnaroek 11y ago`auto` is just bottom-up type derivation, not really type inference. Type inference lets you recover the type of a variable from how the variable is used, not just from how it is initialized. Implementation-wise, bottom-up type derivation only requires unidirectional type propagation, whereas type inference requires solving arbitrary systems of type equations. The former is a special case of the latter, where all equations are of the form “X = T”, where “X” is a type variable and “T” is an arbitrary type expression. No type inference: http://ideone.com/fmm92M http://ideone.com/fmm92M, http://ideone.com/HzyM2E http://ideone.com/HzyM2E Type inference: http://ideone.com/0Gv8fV http://ideone.com/0Gv8fV, http://ideone.com/r9nHUF http://ideone.com/r9nHUF
- dllthomas 11y agoIt's clearly not type inference in its full generality (or all that close, really), but it seems a bit odd to say "X is a special case of Y; A is doing X; A is doing no Y".
- catnaroek 11y agoType inference is performed by scanning the program, generating a system of type equations and solving it. If all type equations are of the form “X = T”, then there's nothing to solve.
- fauigerzigerk 11y ago
- jordigh 11y agoIt certainly has for me. Here is me translating as literally as I could a bit of nontrivial code (which I originally learned from R's C code): http://inversethought.com/hg/medcouple/file/default/jmedcouple.c++ http://inversethought.com/hg/medcouple/file/default/jmedcoup... http://inversethought.com/hg/medcouple/file/default/medcouple.py http://inversethought.com/hg/medcouple/file/default/medcoupl... I'm really happy how almost every Python statement has a nearly equivalent C++ statement. The only one I had trouble with was list comprehensions, but they can be very nearly translated with C++ stdlib algorithms and a few lambdas (kind of looks more like map and filter than a list comprehension, though). The best part is that the C++ code runs as fast and sometimes faster than the original C code I grabbed this from! (The translation path was C -> Python -> C++.)
- netheril96 11y agoAfter C++11, the bottleneck of the speed of development in C++ is no longer the language. But it has numerous other problems dragging down C++ developers still: std::string is close to useless, no userspace and project-scoped package manager, too long build times, hard to debug templates, etc.
- adamnemecek 11y agoIdk dude, after programming in swift for some time, I feel like c++ can't really become a modern language.
- fndrplayer13 11y agoAgree that swift (and other languages like Rust for that matter) offer some very nice advantages over C++. However, C++ is so well established and has a rich collection of libraries and integrations. You can write a library in C++ and ship it on nearly everything. You can also optimize the parts of your system that are well-suited to a systems-language like C++ and then easily expose them in other languages like Python, Ruby, Go, Swift, etc. via their C-bindings. We can't say that (yet) about Swift and Rust. In 3-5 years I think this is going to be a very different conversation, though. In my mind, C++'s flexibility is both its greatest benefit and its greatest danger. You can do almost anything, and there are so many ways to do it. I agree this is a "problem" that's likely not going to be fixed. You can ask your fellow developers to read Scott Meyer's Effective (Modern) C++, you can go to meetups, listen to the wisdom of the steering committee, etc. but at the end of the day it really boils down to the fact that your team needs to be committed to being resilient and responsible. That's true in any language, but much more so in C++.
- nightpool 11y agoRust actually has a really nice embedded library story, and I've already seen a few things in Ruby or Go that have started using Rust libraries for performance. https://github.com/BurntSushi/rure-go https://github.com/BurntSushi/rure-go for example, just to pick something that's crossed my feeds recently. Not sure about Swift, I haven't really been paying attention in that space.
- Animats 11y agoIt's nice to have a "do this to all that stuff" FOR statement, at last. Remember what it was like declaring iterators over collections in FOR statements before AUTO? That was the original motivation for AUTO. But it's much more useful than that. It becomes the common means of declaring local variables.
- catnaroek 11y agoYou could always use `std::for_each` and Boost.Lambda, even before C++11.
- 21 11y agoI would like to borrow some simpler syntax from Python: "if (a)", "for (...)" -> "if a", "for ..." "if ((a > b) && (c > d))" -> "if a > b and c > d" (yes, I know C++ supports "and" if you wish) Or how about accepting a new-line as a ; at the end of a statement (ie: optional ; at line end) I also love nested tuple unpacking: "for i, (key, value) in enumerate(dict.items())"
- GFK_of_xmaspast 11y ago> Or how about accepting a new-line as a ; at the end of a statement (ie: optional ; at line end) And have to use backslashes or something for multiline statements? Ugh.
- andreasvc 11y agoNot necessary. Python allows any open bracket to signal that the line is not terminated yet.
- wmil 11y agoI'll never understand why some people insist on backslashes in paths on Windows. Windows APIs have always supported using forward slashes, using "C:\\path\\to\\file" is just an ugly mess.
- Quiark 11y agoIt doesn't work everywhere, 3rd party libraries would have trouble for sure and I think I had some issues even with Windows or some highe-level Microsoft API too.
- vitaut 11y agoAlso C++ has Python-like formatting: https://github.com/fmtlib/fmt https://github.com/fmtlib/fmt. Disclaimer: I'm the author of this library.
- Negative1 11y agoThis is the kind of broad generalization that someone that knows a lot about Python but very little about other languages would make. The truth is most of these features have existed in other languages for many years, before C++ adoption and in some cases, before Python adoption.
- sklogic 11y agoNot in "some cases" but in "all cases". Python did not introduce anything new in this list.
- nhaliday 11y agoPreshing is a smart guy but this seems to miss the point in a way typical of C++ devs. Python—as with other languages—isn't just a list of features. It also has a guiding philosophy (made explicit in Python's case in https://www.python.org/dev/peps/pep-0020/ https://www.python.org/dev/peps/pep-0020/). C++ doesn't seem to have a guiding philosophy besides "be a Swiss army knife backwards compatible with C." That's OK but I would argue it prevents C++ from every being "Pythonic."
- pjmlp 11y agoThere are many cultures inside C++, but they basically spit into two. There is the one that appreciates C++'s abstraction capabilities with ability to go low level when needed. Cares about writing safe code and sees C copy-paste compatibility as a compromise required to get C++ adopted by the industry. Those developers usually appreciate languages like Ada, Modula-3 and Haskell, and would rather kill the pre-processor. Then there is the culture that somehow had to move from a C compiler into a C++ one, constrain themselves to the C subset of C++ while ignoring the standard library because bloat and write exploit sensitive code as always did in C. Many on the second culture tend to do micro-benchmark driven development. Each code line is questioned how much fast and memory it takes by gut feeling, without any regard from profiler tools or actual needs from the application users.
- santaclaus 11y ago> That's OK but I would argue it prevents C++ from every being "Pythonic." This got me thinking, what would one call an idiomatic C++ style (which I suppose is part of what the core guidelines are trying to push)? Cppthonic? Bjarnic? Python is 'Pythonic,' I usually hear idiomatic Ruby described as the 'Ruby Way.' Is idiomatic Rust 'Rustic'?
- nhaliday 11y agoFor Rust at least there's been some bikeshedding about that https://www.reddit.com/r/rust/comments/33auoe/idiomatic_rust_rustic/ https://www.reddit.com/r/rust/comments/33auoe/idiomatic_rust....
- 11y ago
- sklogic 11y agoFunny how Python narrows the perspective of its practitioners. To brand as "pythonic" all those decades old concepts that had been well known and widespread long before Python is, well, among the most amusing symptoms of a fanboyism.
- cLeEOGPw 11y agoI think Python's, along with languages others mentioned here, popularity is what influenced and partly driven the rapid change of C++. Lisp was around for decades, yet only now, almost right after Python became popular, these old concepts were incorporated.
- paradoja 11y agoThere's a comment by Fabio Fracassi ( http://preshing.com/20141202/cpp-has-become-more-pythonic/#IDComment923313723 http://preshing.com/20141202/cpp-has-become-more-pythonic/#I... ), member of the German delegation for the ISO C++ committee, contending that view. At roughly the same time that Python has been getting this features, many other languages have also been getting them, and usually without crediting Python influence (but rather other languages').
- conceit 11y agoThe problem is that Pythonicity is exclusive. If the features mentioned do correspond between the languages, that's a common property. Although, C++ couldn't be pythonic, if pythonicity describes the necessity to use these features.
- byuu 11y ago> With range-based for loops, I often find myself wishing C++ had Python’s xrange function built-in. Built-in to the language would be nice, but C++ is always extremely spartan with its standard library functionality. Thus: https://gitlab.com/higan/higan/blob/master/nall/range.hpp https://gitlab.com/higan/higan/blob/master/nall/range.hpp 37 lines (without the boilerplate header stuff) and you have: for(int x : range(20)) ...; //iterate from 0 ... 19 for(int y : rrange(myvector)) ...; //iterate from myvector.size()-1 ... 0 Also supports xrange's offset/stride arguments (it's pretty much exactly Python's xrange object in C++.) And you can add support to do ranges over any class anywhere, eg range(myvector) will pull the length from myvector.size() for you with a simple overloaded function. Timing tests in extremely critical loops (like convolution kernels eating 100% CPU usage) shows no discernable performance impact at -O2 and above over the traditional C++-style for(int x = 0; x < size; x++) style.