Python is (not) better than C++

Python is great.

I love it: numbers of arbitrary precision, dictionary keys of any type, easy file reading, stuff like random.sample(xrange(1000), 10)…


But…   Python is being sold for the wrong reasons.

In particular, Python is (of all the languages in all the towns…) compared to C: the archetypal boring, old fashioned and difficult language.  I have a hunch that most of this comes from Python evangelists who endured a grim semester of C but never went on to use C — or rather C++ — in real life.

In reality, different languages are not as different as some people make out.

With Python, you don’t have to worry about memory

Well — sort of. Except that you *do* have to worry about memory, as with any language. Objects take memory. Worry about it.

The difficulties of memory handling in C/C++ are over-rated:
1. Noone uses malloc() and free any more, unless they’re making a mistake or doing something strange or hardcore — in which case they probably know what they’re doing.
2. Most (or many) C/C++ objects are (or should be) allocated on the stack, in the scope of a function — in practice, this works quite like garbage collection in other languages.
3. Lots of C++ code is written using toolkits like Qt, which allocate and free memory for objects and their children created on the heap (i.e. with new) without leaks.

Dynamically typed languages are easier


They’re easier because you don’t have to type in those pesky words like int and double.

…but they’re harder if you’re trying to work out what the hell a long and complex method actually returns, or takes as an argument.

So — a little bit yes, a little bit no.

Python is flexible

Because typing is dynamic? Since when did you need myVar to be ‘spam’ one minute and 42 the next?

Python is terse

So what?

Did you ever look at a piece of old code and say ‘This is wonderfully terse!’

Far better to understand code than admire it.

Python is fun!

This is sort of true.

You get much more ‘bang for your buck’ in the first five minutes of learning Python than for lower-level languages: open(‘myfile’).read() can be pretty exciting if you’re used to file handling in C.

But once you’re up and running, the ‘niceness’ of a language doesn’t really matter. In fact, I sometimes think it doesn’t really matter what language you use: all that matters is how well you know the language and how well you use it.

Self is good, self is explicit

To me this is mystifying.

I think, again, it stems from developers trained academically in C, but unused to actually working with C++. Personally, I’d go nuts if I had to type in self every time I coded in C++. The idea that the self keyword removes ambiguity is… daft. To me, the C _private idiom is a much better alternative to avoid name clashes — and only unusual or very stupid C code has variables at global scope.
To my mind, self is just clutter — and as the first parameter of every method it’s annoying and confusing.

So there.

Python has loads of useful built-in types

Bring on the nasty null-terminated C character strings… Yuk. What a pain. Python strings are so easy! But who in their right minds (with some obvious hardcore caveats) uses C strings?

It seems that certain Pythonistas have never used the C++ Standard Library, let alone Boost or Qt or any of the other toolkits that are a normal part of C++ coding.

Python is instant: no need to compile!

Well… sort of.

Except that still have to wait for source code to be compiled into byte code.

In reality, recompiling a C++ program (if you haven’t changed header files, and/or you’ve structured it well) is not much slower than running the Python interpreter on a Python program.  My Pentium 4 running Visual Studio usually takes 5-30 seconds to recompile and run my (Qt GUI) app in debug mode. Even recompiling the whole program (25,000 lines or so) takes no more than a minute or two.

Bad C/C++ programs have lots of inter-dependencies that make recompilation slow. Good code uses class decoupling and techniques like the PIMPL idiom to keep compilation fast, no matter how large the program.

In the end, it comes down to good code design: sensible idioms, pattern usage, and all the rest. Same for Python, C, C++ and every other language.



About Sam Dutton

I am a Developer Advocate for Google Chrome. I grew up in rural South Australia, went to university in Sydney, and have lived since 1986 in London, England. Twitter: @SW12
This entry was posted in c++, Python and tagged , . Bookmark the permalink.

24 Responses to Python is (not) better than C++

  1. A-Lin says:

    You’ve summed up well what I’ve thought for a while. I’m also a regular user of Python and C++/Boost. Although what I miss the most when I code in C++ is list comprehension, I know one can use STL algorithms but it’s not as nice. Perhaps one day Boost can design something similar for C++.

  2. R.B.S says:

    Your arguments for “Dynamically typed languages are easier” and “Self is good, self is explicit” are hypocritical. In the first you argue that the extra words aren’t that big of a deal but then you go to say that having to type “Self” is clutter. Which is particularly funny since you’re complaining about clutter in Python in comparison to C++…

    • Sam Dutton says:

      You’re right – but that was kind of the point: that there are arguments both ways.

    • James says:

      ‘self’ is one of the most useless things I’ve seen in life. Any decent IDE will show you which are the member variables and which aren’t. Much more useful is the header file with a full list of the member variables, something which is basically missing in Python by the lack of the need to declare variables (with their types) properly.

      Python’s libraries are pretty cool, but the language itself is horrible. It tries to be simple and clear, but often achieves the opposite with its methods to do so.

  3. i needed a quick look at both languages and you gave me the perfect answers. Your thinking is very good and logical and impartial. Thank you.

  4. trent garling says:

    Good summary. I prefer c++ but use python a lot cause its nice fast easy and readable. If your using python your usually prototyping the program or idea and if your using c++ you should already have prototyped the application and now your actually coding the thing for commercial production.

  5. Brian says:

    Anyone who is good at Python is probably good at C++ the reason being Python is a “scientific” or “nerd” language and nerds can certainly handle C++. So you are right, the “ease” argument is somewhat superfluous. Anyone who can handle first-class objects, metaclasses and data structures (the heart of Python) can handle C++ with enough time especially C++11 with automatic pointers.

    I think the main barrier is C++ isn’t considered a “web” language. Python is more a “scripting” language and meshes well with Javascript and as a web backend with Sinatra-like frameworks. But Emscripten and native in the browser is bringing this crashing down in a rather alarming way. I am considering pausing all my web development outside of work and just diving completely into C++ for the next year (or two). Especially with C++11 it seems like there is no excuse to use managed code only, and it feels like native is coming back with a vengeance. I don’t want to be the only web developer who doesn’t have serious native projects in a few years. Soon kids fresh out of computer science with no web application, networking or database experience but with 4 years of C or C++ will churn out great things in the browser. What takes years of experience with database design, Javascript and the DOM will take months or weeks once native becomes ubiquitous. This is a strange instance of the bar being raised and will be a shock to the unprepared. I just hope I can get ready in time.

  6. Steven Chartis says:

    I agree that having absolutely dynamic variables is a kindave useless feature, but being able to use Int and Float types interchangeably is pretty nice. Also, Python numbers are nearly unlimited size, which makes calculations easier to implement. I still enjoy coding in C and C++, however.

  7. Ankush Thakur says:

    I am so thankful! Your post has calmed me down and settled months of searching. I’m now convinced that I like the raw power of C/C++, and given that I’ve spent quite a lot of time programming in it, this should me my main choice. Python is great, but maybe “niceness” is a bit overrated! 🙂

  8. Rei-chan says:

    Heh, you don’t get `self`, like, at all. Sorry to be rude like that.

    (Yay, commenting a 2008 post!)

  9. guardian says:

    Well, choosing the right language for a task is often based on checking available free libraries.

    For the Web: Python has framework like django. C++ has Wt. They are very difficult to compare since Wt has widgets out of the box ( no javascript / CSS / Template ) to write. Django has automatic admin interface, Inegrated ORM (evil for perf, but fine for 99.99% web apps)…

    Science: Mayavi and Scipy are definitely awesome. Most things are as fast in Python as in c/c++, beacause you just call a few functions from c Modules.

    High Perf: You need very high perf ? Maybe automatic arbitrage trading ? The fastest makes the trade and the other looses ? Super computing ? Well, definitely, When you go low level, memory pools and intrusive datastructures libraries are awesome. c++ wins.

    Low level: Well, to write an interpreter or virtual machine, at some point you’ll need a compiled language. DBMS, OS, RT systems … C more often than C++ is the way to go.

    There are plenty of cases, for instance, PDF handling is so much simpler with Report Lab than with libharu… One example from algorithmic contest often quoted, “compute 25!” when the standard library has bigints you are fine, else you are screwed…

    C is lacking a proper library, GLIBC is not very complete, but C is often much easier than c++, You do not have to wonder what the compiler is doing for you (try to gess the assembly code generated when you use Boost::spirit …). Python is Very terse and readable, and when you want to focus on algorithm and problem solving it can save you time not to wonder about low level stuffs. C has plenty of libs that works even when you have no OS ( thanks to OS writters sharing their libs )

  10. Mihail says:

    I’m currently working with all 3 languages and have to fine tune all 3 of them and here’s what I’m finding.
    c++ can handle resources for you unless you don’t mind your application being slow as a slug, in which case you are better off with python… I’m maintaining an app that reads some string data from files ( about 2 GB worth of) does some string crunching .. and outputs the result in another file.. ( 300 Mb worth of.. ). The application has been written to avoid resource management as you said, by making use of the stack.. and a full cycle goes in 25 minutes. Prototyping the same operation in python ended up producing the same results in 3 minutes, at half the ram usage..
    Now why is that? Well, the answer relies on how the languages behave.. so let’s start with python.. Which, like java, for non fundamental types, will always passes by reference and, unless you explicitly ask to, it will always return by reference, which is fast. C++, on the other hand is meant to be backwards compatible with C ( to which it unwinds), and will always pass and return by value, making copies in the process. Thus C++ will always make full copies of your objects when you pass or return. This is fine for small objects, but even strings become a slowdown and use quite a lot of memory if you call them a lot. Now C++ added some magic with implicit reference casting, when const foo& bar, and the newer operator =&& for returns, which is supposed to move your data from the right side of = to the left, however this still requires the presence of the object in the outside scope to which the data gets moved, or makes your object unchangeable on return. const_casting just begs for trouble if you think of forcing it. So now, you have an interesting mix of pointer vs reference, 2 ways of allocating/deallocating memory and a half baked template library with generics that don’t support references in containers. And to add salt to the wound, if you have a class that’s not concise to the compiler, it will be up to you to implement the operators to support move rather than copy.
    All in all, if you want decent performance you need to avoid copying data, in which case you either use a language that supports that, or you can’t avoid pointers or references ( whatever poison you prefer).

    • Yoda says:

      Could you be more specific about this, you must be doing something severely wrong ? I too, handle multi-GB files in C++ without any of the problems you just described. C++ also does not unwind to C and also C++ lets you, more than any other language, control the number of copies that have to be made.

  11. Uh Huh says:

    Python would not exist without C 🙂

  12. parisian says:

    C would not exist without assembler.
    Assembler would not exist without machine code.
    Machine code would not exist without binary.
    Binary would not exist without cpu wires
    cpu wires would not exist without transistors
    transistors would not exist without silicon
    silicon would not exist without sand
    sand would not exist without the formation of the earth
    the formation of the earth would not exist without lisp
    lisp would not exist without maths
    maths would not exist without a higher being
    a higher being would not exist without a purpose
    a purpose would not exist without life
    life would not exist without material
    material would not exist without process
    process would not exist without machinery
    machinery would not exist without intelligence
    intelligence would not exist without algorithms
    algorithms would not exist without lisp
    lisp would not exist without lisp
    therefore lisp exists.

  13. Pingback: Immortalization of this Anomalous Poetry | Matt

  14. James Lu says:

    Python’s greatest advantage is it’s libraries. C++ libraries are few and far between. There are over 72k libraries on PyPI alone. It’s easier to be able to return None instead of returning a pointer and having to deal with a pointer. In Python, we now have type annotations. We can now easily debug and still have the benefits of dynamic typing. C++ has an incredibly hard to use standard library with bad names and no OOP. There is not string split function. Functions like stoi should be string members. Python is easier to read. Python takes less time to develop, more time to run. In very few applications CPU time is more important than dev time.

    • NewtonsWren says:

      That thinking is a large reason why netbooks flopped. Without at least 4GB of RAM, 64GB of storage, and dual core processors, its damn near impossible to run anything. And if you can run something, it’s the only thing you can run because it’s so resource intensive.

      Now I get it, it’s hard to have a Ferrari for each day of the week if we extend dev time, which is why Profit is a dirty word. But we should still focus on software that doesn’t murder resources for the sake of it.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.