208 points · by underyx · 12y ago · 176 comments
Dynamic typing makes Python easier to use than C
I disagree with the implications. The main reasons Python is easier to use is independent of type system. Not having to manually manage memory, for example! Overall it is a higher-level language, whereas C is designed for maximum performance.Dynamic typing is probably preferable to a 40 year old type system. But Python could be easier to use (catch bugs ahead of time!) and execute faster by adding a modern type system. Optional typing (like TypeScript or Facebook's new PHP implemntation) would probably be appropriate.
> Overall it is a higher-level language, whereas C is designed for maximum performance.
I agree with most of your points, but on this I think you are comparing apples to oranges. C is not designed for maximum performance, but as a system language and as such only as slim abstraction over assembler. As a side effect it allows for maximum performance. A more fair comparison (pretty much every widely used language is easier to use than C) would be C++ vs. Python, where in C++ most - if not all - of the higher level abstractions were explicitly designed not to worsen performance compared to low level code. And in my opinion Python is so much easier to use than C++ because it values simplicity and consistency more than efficiency.
For example the general loop constructions in Python which are possible because of nice generators and the wonderfully straightforward `yield` construction are unacceptable in C++ as they lack the flexibility to be as efficient as possible in every case.
The advantage of dynamic typing only becomes apparent in a third argumentative step; when you try build a language with consistent and efficient abstraction and you end up with something like Haskell whose type system complexity is huge entry barrier. That's why I think dynamic typing is good for Python.
I'd argue that Haskell actually has a pedagogy problem, because many of its proponents are academics or mathematicians, who are comfortable with that kind of language. Talking about monads, functors, and arrows is a very natural activity for them, and clarifies rather than complicates the subject. However, you don't really have to understand any of that to get started in Haskell, and much of the blogging community has (I think wrongly) focused on explaining advanced concepts rather than making easy introductions.
You don't have to deal with monads any more than you have to deal with Python's OO behavior - which is to say, for quite a while.
I'd also argue that once you take in to account the sometime strange OO implementation of Python, and that Haskell has type inference for most things, Haskell is easier to understand the high level concepts in. Typeclasses and higher order functions (functions which act on functions) provide a very neat way to substitute in different types to your algorithm without having to change the whole thing, and don't even delve in to the complicated world of functors and monads.
I would like to make two notes about this:
- Most of the Haskell tutorial examples are about computing pi, fibs, and other math functions or series. Which is fine, but rather obvious beyond the recursion vs iteration bit. It's not just that newcomers arrive to Haskell with an imperative mindset, it's that they (we?) come with imperative (stateful) algorithms, which of course turn out to be a nightmare to implement.
- I found those explanations about Monads, etc necessary because as soon as I wanted to do anything less obvious than calculating a function or series, it was pretty hard to figure out how to get it done. For example, adding print logs to my code to debug, or building the code to output the formatted result of my program. "Why can't I use map here?" "What is is this mapM thing?" are very real roadblocks.
Those problems are not unique to Haskell, of course, but Haskell's purity makes it much more inflexible - you can't do some part the Haskell way to learn the ropes while you do the rest imperatively to get actual, satisfying results.
main = do
putStrLn "Hello, what's your name?"
name <- getLine
putStrLn ("Hey " ++ name ++ ", you rock!")
The monad effectively introduced a separate syntax for declaring variables, which you must use in preference to let/where, and the compiler will emit a gibberish error message if you mix them up. So you must acquire at least a working understanding of monadic syntax before you can write a trivial program.Btw. I am a mathematician and the only time I ever had contact with category theory was in a seminar presentation. The great majority of students at our university would be as new to functors as most of you.
But on the other hand the reason I am fascinated by Haskell are all these advanced methodologies that promise to make the act of solving a problem more manageable. To contrast that against the Python/C comparison I find that Python gets less in my way (probably even less than any other programming language I've tried) but hasn't taught me concepts that I didn't already know from C++/Java/…
So the question would be: If you don't want to learn about Monads, why would you come to Haskell in the first place?
For sure. Then you get a compiler error.
Programming Haskell without understand the type system and lambda calculus is not possible.
Edit: thanks for downvoting me. If you believe that you can program Haskell without understanding the basics of Functional Programming and without understanding the type system, then you live in an alternate reality or want to evangelize Haskell.
Haskell borrows concepts from category theory (a "field" so abstract from most math that most mathematicians don't need but a handful of its concepts) to label typeclasses, and those typeclasses don't always follow from their namesake.
Further, Haskell could exist and keep its property of referential transparency without the the 'mathematical' structures or their names. Here's a version of Haskell without monads: http://donsbot.wordpress.com/2009/01/31/reviving-the-gofer-s...
Monads, functors, arrows, etc. are more aesthetic than fundamental to the core nature of Haskell. They're just a bookish (and sometimes bureaucratic, IMO) design choice. What I mean by that, is that the language designers took a concept (referential transparency) and built an understandable structure, but beside and aside from this, made a bunch of nested, derived typeclasses of dubious value or purpose. Sometimes I look at a Haskell library and have a more academic version of the, "Why the fuck is this a class?" moment.
I'd like to comment tangentially that Haskell is almost the OOP/Java of the 2010's - the programming community claims that it makes your code "safer", and in some sense it very much does, but its features are being perverted and overhyped while its caveats are being forgotten.
I very rarely change the type of a variable, so it would be essentially free speed and free speeds for me.
I actually wonder, do people use dynamic typing so often? I mean, it's nice to do "variable = int(variable)" when I know that I'm getting an integer in a string, but that's probably the only use case can I can think off that doesn't just reuse variables for something else.
Here are a few from Guido himself (not really anti static-typing, but just walking you through pros/cons as he sees them). Great reads:
http://www.artima.com/weblogs/viewpost.jsp?thread=85551
Can someone give me a concrete example of when static typing would be beneficial? (The majority of my work revolves around databases, so I guess I rely on that as a kind of type checking to a degree).
On the other hand, the Haskell typing is superior in many ways to dynamic typing. Because you lose very few power of expression but you gain a lot of time in your workflow (and also security).
Concrete example (I'll use js):
function showField(data) {
console.log(data.field1.filed2);
}
you relaunch your application, you click on three to four elements, then you enter your name and a password. You click on the button, and "BAM, filed2 doesn't exists".
Correct the typo or add a test and replay the game of executing your new code.Static typing:
showField : ConcreteData -> IO ()
showField data = putStrLn $ filed2 (field1 data)
Try to compile, get the error:
showField : filed2 doesn't exists, may be you mean "field2".correct your code. Now you're done.
Here is another example:
Dynamic typing:
function showField(data) {
if (data.field) { console.log("OK"); }
else { console.log("Not OK")}
}
...
showField(myData);
Try it using all manipulations to reach the test case, then:
ERROR, couldn't find field for null. :-|
replace by if (data && data.field).In static typing:
showField data = if (field data)
then putStrLn "OK"
else putStrLn "Not OK"
compile: could not match String with (Maybe String) at ...
now: showField data
| field data == Nothing = putStrLn "Not OK"
| otherwise = putStrLn "OK"
You fixed it, but you didn't had to lose your time searching
the error.The BIG bonus is that you detect the error before you discover it at runtime. Imagine you didn't detected the error during your test (even with unit tests). This is why it is so easy to push this kind of error in production in a dynamic typed language.
And I only scratched the surface.
I program mostly in JS now, and I love even more when I am doing Haskell.
I can't understand what a function is doing in isolation when the types are unknown. A function takes a variable foo and returns foo[bar], what did it return? Is that even valid code? What does that even mean if foo is a string and bar is a database handle? Ok, this is a lookup of some kind... is it an index or a hash table? I have no way of knowing without reading the comments (which may or may not exist). The only other way to figure out what the function is used for is to trace the data all the way back to its creation... literally find every call site and slog my way up the call stack.
In a dynamic language you can't even tell if all your code will execute until you run it and test all the code paths, let alone attempting to convince yourself that it's correct. I don't understand why people want that cognitive burden when the compiler can tell you straight away that you've typed something nonsensical.
I've just never seen a code sample that made me want to throw away static typing. Not even one.
The best compromise between static typing and dynamic typing, IMHO, is what C# (and later generations of C++) do: implicit typing via the VAR keyword.
You can't implicitly type the members of an object or the arguments of a function, but you can implicitly type variables in local scope. This is how C# is able to support anonymous types and functions so easily - implicit typing abstracts away the gangly looking static objects that are produced by LINQ queries and the like.
Implicit typing makes it very easy to refactor large blocks of statically typed code without compromising the benefits of static typing. So you get some of the flexibility of dynamic typing with the predictability of static typing.
Realistically - you don't utterly redefine the type of objects at runtime very often in production code even with dynamic languages, so you don't lose much with implicit typing.
More information makes the code somewhat readable and understandable 10 years after when it was written. Dynamic typing often becomes a much more messy affair.
Static typing is beneficial when you want to catch a certain type of errors before your code enters production, it makes you write less error prone code.
I program a lot in Groovy these days, and it now has optional static typing with a limited amount of type inference. What I observe is that I voluntarily prefer to type my variables much of the time because it really does save time and takes only a fraction more effort than leaving them untyped. I find Python quite hard to decipher much of the time because it's nearly impossible to know what type a variable passed into a function is unless you trace back to the caller.
The general argument is that if you write enough unit tests, you can guarantee that your code doesn't make those kinds of mistakes. The statically-typed response is "why should you have to write unit tests when the compiler can make that guarantee for you?"
The interesting thing is that a sufficiently powerful type system with strong type inference eventually converges with dynamic typing in ease of use, but it offers the option to do rather complex reasoning about the code at compile time, again, preventing certain classes of errors.
Beyond the classes of errors being prevented, I feel like a mature, strongly typed architecture offers a certain amount of guidance in implementing new solutions. If you start implementing certain interfaces in our more mature codebases, you get a number of situations you need to handle - since the interface forces you to implement certain methods. You can't forget these situations, again, preventing mistakes or recreating the same bugs.
Note that both situations assume a certain level of maturity in a solution. Initially, a type system can be somewhat annoying while you work out the kinks, I'm perfectly fine to admit this. This requirement also implies what I feel - in small, hacky scripts, static type systems tend to be annoying to some degree. But in large, complex systems, I don't want to miss them.
Result: program crashed when trying to call not present method. Had to clear up a few of these before it would work. If the type system hadn't been so forgiving the library implementers would have realized how their abstractions were leaking, and it would have been a lot easier for me to implement the interface correctly.
A similar thing can be achieved in Haskell, with the Typeable typeclass. The Scrap Your Boilerplate also fixes problems like this.
There has to be some use for dynamic typing when even Haskell (ghc) adds support for it, I guess.
I don't think ML users will agree ;)
ML dates from the 70s and its type system is the inspiration for Haskell's, although Haskell also adds typeclasses (and various Haskell extensions add a bunch of other stuff).
The most widely used versions today are Standard ML and Ocaml, although many languages take inspiration from ML, for example Coq, Haskell, Clean, etc.
I assume by "new PHP implementation", you're referring to Hack[2] which is a different language, although heavily based on PHP. (I believe Hack is a superset?)
https://github.com/psoberoi/stepanov-conversations-course/tr...
I certainly don't see Cython as anything but a quick way to get efficient C code in to Python module though... you typically get the worst of both worlds with compilation + dynamic typing.
Regardless, it's damned nice (especially with TypeScript on the front end: static optional typing everywhere!)
http://docs.cython.org/src/tutorial/cython_tutorial.html#pyx...
At the same time I hate it when syntax vacillates wildly from application to application.
At the same time it is 40x faster (in my applications developed in a fortune 500 company, ok the research bit - but still delivered for use if not prod) than python.
Now, if only we got it running in SPARK...
It wouldn't make Python easier to use. Just the opposite.
The biggest reminder of this was Python 3, which for me was a complete disappointment. They could have limited python's super-dynamic behavior (e.g. changing builtin functions, patching classes on the fly, etc.) or made them optional. They could've added optional typing annotations a la Cython. Or even changing the builtins and language syntax to allow more inplace operations and preallocations, so that temporary results wouldn't have to be allocated on the heap over and over again. All of these changes would have made python faster and more JIT-able. None of these things happened. Performance-wise, python 3 is no step forward.
Python+Cython is still a powerful combination, but eventually Julia or similar languages will eat python's lunch with respect to scientific computing.
Dynamically typed does not imply no types. A good CL implementation takes that to heart and produces really nice code out of the box. And the language spec provides for an API to allow program developers to specify types and hints to the compiler to optimize certain functions and code paths where it's needed.
The benefit from this is that you can rapidly prototype your application and harden it to the platform you deploy on when performance becomes an issue... and with built-in conditional compilation you can do that in a cross-platform way.
The chief problem is the high level of dynamic typing going, plus the huge amount of globally-changable assumptions (you can add methods to any instance of a class, you can globally change the definition of language built-ins, etc.)
Common Lisp not only provides type hinting facilities in the language it also provides hinting to the compiler to turn off all run-time type checks in critical code sections.
I don't meant to say USE LISP (but you know, it's available and ready to go!), but I do mean to say: the knowledge (algorithms, research papers, implementations) on how to do this relatively efficiently was developed in the late 70s and early 80s.
edit: SBCL is a good example of what can be done with this knowledge. I would be 100% unsurprised if perl/python/ruby could benefit from these algorithms. See phkoung's blog for what he did with SBCL on numerical analysis and high performance Lisp.
So we all know the research, and we know how to put it into practice to make both Ruby and Python run very efficiently. There's no question that Ruby and Python can benefit from this work, because it's already been done many times. What does not look tractable is cramming it all into the existing code bases of CPython or MRI.
The exception is when you allow yourself to annotate your code with type information, which allows you to eliminate a lot of the code you'd otherwise emit. Python for instance allows you to do this with Cython/snakeskin/etc., so the technique (that I think) you're talking about is applied there, because it is effective.
There's a more subtle benefit as well. Because compilability was a key goal in the design of CL, using it as a translation target while you're designing a new dynamic language will help you make sure your language is also efficiently compilable.
EDITED to add: in CL, the whole tagged-pointer thing has been taken care of for you, so you don't have to think about it (cf. [0]). This means you get fixnums (unboxed immediate integers), with automatic overflow to bignums (arbitrary-precision integers), for free. In fact there's the whole CL numeric tower, including ratios and complex numbers. Other goodies: multiple inheritance. Multimethods (multiple dispatch). Class creation and redefinition at runtime.
It baffles me that anyone would want to reimplement all that stuff, or even part of it.
[0] https://mail.python.org/pipermail/python-dev/2004-July/04614...
Like CLOS.
At the point where even Google can't make it happen, it really starts to look like Python performance is limited at some very fundamental level to what we see today. Personally I think this is fine. I use Python for everything day-to-day and offloading the intensive stuff to a C extension (a la Numpy) works just great. There are very few instances where I find myself wishing Python was faster.
The difference between Unladen Swallow and V8 is that while V8 was "make JavaScript fast on the workloads we care about by any means necessary", Unladen Swallow was "make CPython fast without disturbing the implementation's interface to native extensions". A V8-style approach to speeding up Python might well be practical even if a project with Unladen Swallow's constraints to using, and preserving the same relationship to extensions, was not.
> At the point where even Google can't make it happen, it really starts to look like Python performance is limited at some very fundamental level to what we see today.
For the reasons above, "Google can't make it happen" isn't really a good description. Google choose to try with constraints it didn't apply to JavaScript, because for their purposes with Python -- unlike their purposes with JavaScript -- if they were going to go with an unconstrained approach, then they were quite happy tossing the language aside. OTOH, with V8, running actual JavaScript was important but existing external modules called from JavaScript weren't a constraint, so the interpreter had fewer constraints than with Unladen Swallow, and making the language faster (rather than getting something faster, but not necessarily keeping the same language if it made anything else more difficult) was a higher priority.
So V8 succeeding while Unladen Swallow fails isn't necessarily a sign that making a fast Python interpreter is harder than making a fast JavaScript interpreter -- making a fast JS interpreter (language non-negotiable) was a priority for Google, making Python faster if it could be done was a nice-to-have that wasn't worthwhile if it doing it in Python was disruptive enough that they wouldn't be able to leverage their existing library of stuff-built-to-interface-with-CPython without additional effort. The efforts weren't parallel, and the results aren't comparable.
[1] http://qinsb.blogspot.com/2011/03/unladen-swallow-retrospect...
PHP companies tend to have more of an issue with this, for various reasons. PHP apps can suffer from the "big ball of muck" issue quite easily, where there's not nearly enough abstraction to allow for parts of the code to be written in other languages. Such an architecture would also require additional deployment steps, vs PHP's "copy everything to the right place", and there's a lot of PHP devs who, while rather good at PHP, are quite resistant to new languages.
Also, extension modules, Pillow, Numpy, Scipy, Pandas greatly reduce need to make Python it self faster.
... efficient use of development time ...
That is the reason, why Python counts (not only references). Python has many very good libraries, is a good OOP language, easy to learn, but still very, very powerful. You can express in Python some things in a single line, where you need hundreds of lines in C++ or other languages.The few percent of running speed that you might loose, are neglect-able in most cases against the win in development speed.
In many applications you don't need the full CPU power, but often times you are hindered by e.g. the disk speed or other factors ... and than you don't lose anything when you are a little bit slower in some minor tasks.
citation needed.
The headers alone for STL maps are hundreds of LOC.
C++11:
map<int, char> x = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};
Any not-ancient C++ using boost Assign:
map<int, char> x = map_list_of (1, 'a') (3, 'b') (5, 'c') (7, 'd');
Shamelessly stolen from here:
http://stackoverflow.com/questions/138600/initializing-a-sta...
#include <map>
#include <vector>
#include <string>
#include <boost/any.hpp>
using boost::any;
using std::map;
using std::string;
using std::vector;
int main() {
map<string,any> x = {{"foo", 34}, {"bar", vector<int>{1,2,3}}, {"bar", "quux"}};
}
Syntax overhead amortizes to constant factor ;)Also one little hint: Use Cython for enhancements. Cython is great for implementing small enhancements when you don't want to hassle with refcounts and the normal Python API. Also your enhancements are automatically compatible to Python 2 + Python 3. You can also call C functions from Cython very easily for full speed. Cython is really great, when you don't need to optimize to the last nanosecond.
This is pretty close to how I characterize my time, 'doing X with code', and Python yields great returns in these terms.
I just switched my program from using a defaultdict to a regular dict.
I.e., from defaultdict(lambda:'NA') to regular dict using get(val, 'NA') for access.
And I got a something like a 100x speedup. It runs in two minutes instead of two hours. I had no idea a defaultdict would be so much slower.
Unless there's something funny going on in my program and it's unusual behavior.
And they pretty much say that there is only one method that's been overridden from the normal dict class. And all it does is it executes the anonymous method (lamda) you supplied instead of returning the default value you pass in.
Also, this depends on your usage, and what you have in the lambda expression. I'm curious about your code, care to paste/link some of it for us?
Where defaultdict shines is the case where you hit an entry a bunch of times, but you'd like to automate initializing an entry the first time it is hit.
The most common example is probably the frequency distribution, where the frequency needs to start out zero and be incremented each time a key is seen. Using int or lambda:0 as defaultdict's argument works fine for the simple case. If you want to tabulate more than just the count, e.g. a count and one or more sums, you can pass a constructor that produces an object with an update method, to which you pass whatever your key represents.
Simple microbenchmark: http://pastebin.com/vkacByzp
It appears that defaultdict saves time as well as code for the normal use case.
Also, it is worth asking if for majority of use cases of python for data/analysis, the ease and flexibility outweights the slowness.
Virtual functions in C++ which allow some form of dynamic behaviour are slower than static function calls because they inherently involve another level of indirection. Static calls are known at compile time, they can be inlined by the compiler, they can be optimized in the context in which they're called. Now, nothing prevents the C++ run-time from trying to do the same thing at run-time but you can relatively easily see that it'll have to make some other compromised to do so. Nothing prevents a C++ program from generating C++ code at run-time, compiling it, and loading it into the current process as a .so. Now that's a pretty dynamic behaviour but there's again an obvious price. You can also write self modifying code. At any rate, static languages are capable of the same dynamic behaviour that dynamic languages are capable of but you often have to implement that behaviour yourself (or embed an interpreter...).
Fundamentally, a dynamic language can't make the kinds of assumptions a more static language can make, it can try and determine things at run-time (ala JIT) but those take time and still have to adapt to the dynamics of the language. The same line of code "a = b + c" in Python can mean something completely different every time it's executed so the run-time has to figure out what the types are an invoke the right code. Now the real problem is that if you take advantage of that then no one can actually tell what this code is doing and it is utterly unmaintainable.
To compound the problems facing dynamic languages is the fact that CPUs are optimized for executing "predictable" code. When your language is dynamic there are more dependencies in the instruction sequence and things like branch prediction may become more difficult. It also doesn't help that some of the dynamic languages we're discussing have poor locality in memory (that's an orthogonal issue though, you could give a dynamic language much better control over memory).
EDIT: One would think it should be possible to design a language which has both dynamic and static features where if you restrict yourself to the static portion runs just as fast as any other statically compiled language and still allows to switch to more dynamic concepts and pay the price when you do that.
(And yes, I know I'm just adding to the people plugging Julia here) Among other things, Julia actually avoids forms of dynamism that are in practice rarely employed by programs in dynamic languages. Existing code is immutable, but new code may always be generated if different behaviour is desired.
I'm not entirely sure if I could accurately say Julia allows one to trade between efficiency and dynamism when each is desired, but it does appear to be a much better balanced approach than is normal.
Common List on SBCL is often faster than F# on Mono, eve though Mono is statically typed, as the former runtime has had a lot more work put into optimising it.
Or, compare F# on Mono with Clojure on the OpenJDK: http://benchmarksgame.alioth.debian.org/u64q/benchmark.php?t...
Clojure again is faster, due to a more optimised runtime.
A more interesting counter example would be LuaJIT, since it has to support completely dynamic code with a fair bit of monkey patching going on. But that is more of a showcase for tracing JITs being fairly powerful (for hard to predict code bases) than that indirections are cheap.
Previously I had thought that doing a=110 creates an object 'a' that stores the value 110 (and when we do b=a, b simply points to a). I had no idea there is a third object in play.
Which means that, if you execute "a = 110" a bunch of times, no new objects get created. If you execute "a= 110+300" a bunch of times, a whole bunch of new objects is created and destroyed.
By the way, this boxing/unboxing logic is also at work when you stick numbers into a standard HashMap, since it stores Integer objects and not the primitive type. However, in Java you can use GNU Trove's IntObjectHashMap or ObjectIntHashMap and save some memory, whereas Python's "everything is an object" rules this out (unless you're using PyPy and its tracing jit which figures out that a always contains a number).
That's not to say that OO is necessarily the ideal language paradigm, but it has certainly been the most dominant in the era Python has existed.
http://www.laurentluce.com/posts/python-integer-objects-impl...
>>> a = 110
>>> b = 110
>>> id(a) == id(b)
TrueThat's a sticking point with a lot of young Java programmers encountering boxed types for the first time. They see that x is true here:
Integer x = new Integer(5);
Integer y = new Integer(5);
x == y
But this is false: Integer x = new Integer(5000);
Integer y = new Integer(5000);
x == y
(The real fix, of course, is to use the 'equals' method when comparing objects.) > binary_add<int, int>(a, b)
no... there is simply not function call overhead for adding two integers in C.The very first part says that this is only a writeup for people who are not intimately familiar with why "dynamically typed" might slow down Python.