91
votes

I've been using python for a few days now and I think I understand the difference between dynamic and static typing. What I don't understand is under what circumstances it would be preferred. It is flexible and readable, but at the expense of more runtime checks and additional required unit testing.

Aside from non-functional criteria like flexibility and readability, what reasons are there to choose dynamic typing? What can I do with dynamic typing that isn't possible otherwise? What specific code example can you think of that illustrates a concrete advantage of dynamic typing?

16
  • 5
    Theoretically there's nothing you can't do in either, as long as the languages are Turing Complete. The more interesting question to me is what's easy or natural in one vs. the other. There are things I do regularly in Python that I wouldn't even consider in C++ even though I know it's capable. Commented Oct 3, 2012 at 21:19
  • 28
    As Chris Smith writes in his excellent essay What to know before debating type systems: "The problem, in this case, is that most programmers have limited experience, and haven't tried a lot of languages. For context, here, six or seven doesn't count as "a lot." ... Two interesting consequences of this are: (1) Many programmers have used very poor statically typed languages. (2) Many programmers have used dynamically typed languages very poorly." Commented Oct 3, 2012 at 21:38
  • 3
    @suslik: If language primitives have nonsensical types, then of course you can do nonsensical things with types. That has nothing to do with the difference between static and dynamic typing.
    – Jon Purdy
    Commented Oct 4, 2012 at 4:36
  • 10
    @CzarekTomczak: That is a feature of some dynamically-typed languages, yes. But it is possible for a statically-typed language to be modifiable at runtime. For example, Visual Studio allows you to rewrite C# code while you're at a breakpoint in the debugger, and even rewind the instruction pointer to re-run your code with new changes. As I quoted Chris Smith in my other comment: "Many programmers have used very poor statically typed languages" -- don't judge all statically typed languages by the ones you know. Commented Oct 4, 2012 at 15:33
  • 11
    @WarrenP: You assert that "dynamic type systems reduce the amount of extra cruft I have to type in" -- but then you compare Python to C++. That isn't a fair comparison: of course C++ is more verbose than Python, but that's not because of the difference in their type systems, it's because of the difference in their grammars. If you just want to reduce the number of characters in your program source, learn J or APL: I guarantee they'll be shorter. A more fair comparison would be to compare Python to Haskell. (For the record: I love Python and prefer it over C++, but I like Haskell even more.) Commented Oct 4, 2012 at 15:38

7 Answers 7

49
votes

Since you asked for a specific example, I'll give you one.

Rob Conery's Massive ORM is 400 lines of code. It's that small because Rob is able to map SQL tables and provide object results without requiring a lot of static types to mirror the SQL tables. This is accomplished by using the dynamic data type in C#. Rob's web page describes this process in detail, but it seems clear that, in this particular use case, the dynamic typing is in large part responsible for the brevity of the code.

Compare with Sam Saffron's Dapper, which uses static types; the SQLMapper class alone is 3000 lines of code.

Note that the usual disclaimers apply, and your mileage may vary; Dapper has different goals than Massive does. I just point this out as an example of something that you can do in 400 lines of code that probably wouldn't be possible without dynamic typing.


Dynamic typing allows you to defer your type decisions to runtime. That's all.

Whether you use a dynamically-typed language or a statically-typed one, your type choices must still be sensible. You're not going to add two strings together and expect a numeric answer unless the strings contain numeric data, and if they do not, you're going to get unexpected results. A statically typed language will not let you do this in the first place.

Proponents of statically type languages point out that the compiler can do a substantial amount of "sanity checking" your code at compile time, before a single line executes. This is a Good Thing™.

C# has the dynamic keyword, which allows you to defer the type decision to runtime without losing the benefits of static type safety in the rest of your code. Type inference (var) eliminates much of the pain of writing in a statically-typed language by removing the need to always explicitly declare types.


Dynamic languages do seem to favor a more interactive, immediate approach to programming. Nobody expects you to have to write a class and go through a compile cycle to type out a bit of Lisp code and watch it execute. Yet that's exactly what I'm expected to do in C#.

15
  • 22
    If I added two numeric strings together, I still wouldn't expect a numeric result.
    – pdr
    Commented Oct 3, 2012 at 20:40
  • 22
    @Robert I agree with most of your answer. However, note that there are statically-typed languages with interactive read-eval-print loops, such as Scala and Haskell. It may be that C# just isn't a particularly interactive language.
    – Andres F.
    Commented Oct 3, 2012 at 20:57
  • 14
    Gotta learn me a Haskell. Commented Oct 3, 2012 at 21:25
  • 7
    @RobertHarvey: You might be surprised/impressed with F# if you haven't already tried it. You get all of the (compile-time) type safety that you normally get in a .NET language, except that you rarely ever have to declare any types. The type inference in F# goes beyond what's available/works in C#. Also: similar to what Andres and Daniel are pointing out, F# interactive is part of Visual Studio... Commented Oct 3, 2012 at 21:40
  • 8
    "You're not going to add two strings together and expect a numeric answer unless the strings contain numeric data, and if they do not, you're going to get unexpected results" sorry, this has nothing to do with dynamic vs static typing, this is strong vs weak typing.
    – vartec
    Commented Oct 5, 2012 at 12:50
26
votes

Phrases like "static typing" and "dynamic typing" are thrown around a lot, and people tend to use subtly different definitions, so let's start by clarifying what we mean.

Consider a language that has static types that are checked at compile-time. But say that a type error generates only a non-fatal warning, and at runtime, everything is duck-typed. These static types are only for the programmer's convenience, and do not affect the codegen. This illustrates that static typing does not by itself impose any limitations, and is not mutually exclusive with dynamic typing. (Objective-C is a lot like this.)

But most static type systems do not behave this way. There's two common properties of static type systems that can impose limitations:

The compiler may reject a program that contains a static type error.

This is a limitation because many type safe programs necessarily contain a static type error.

For example, I have a Python script that needs to run as both Python 2 and Python 3. Some functions changed their parameter types between Python 2 and 3, so I have code like this:

if sys.version_info[0] == 2:
    wfile.write(txt)
else:
    wfile.write(bytes(txt, 'utf-8'))

A Python 2 static type checker would reject the Python 3 code (and vice versa), even though it would never be executed. My type safe program contains a static type error.

As another example, consider a Mac program that wants to run on OS X 10.6, but take advantage of new features in 10.7. The 10.7 methods may or may not exist at runtime, and it's on me, the programmer, to detect them. A static type checker is forced to either reject my program to ensure type safety, or accept the program, along with the possibility of producing a type error (function missing) at runtime.

Static type checking assumes that the runtime environment is adequately described by the compile time information. But predicting the future is perilous!

Here's one more limitation:

The compiler may generate code that assumes the runtime type is the static type.

Assuming the static types are "correct" provides many opportunities for optimization, but these optimizations can be limiting. A good example is proxy objects, e.g. remoting. Say you wish to have a local proxy object that forwards method invocations to a real object in another process. It would be nice if the proxy were generic (so it can masquerade as any object) and transparent (so that existing code does not need to know it is talking to a proxy). But to do this, the compiler cannot generate code that assumes the static types are correct, e.g. by statically inlining method calls, because that will fail if the object is actually a proxy.

Examples of such remoting in action include ObjC's NSXPCConnection or C#'s TransparentProxy (whose implementation required a few pessimizations in the runtime - see here for a discussion).

When the codegen is not dependent on the static types, and you have facilities like message forwarding, you can do lots of cool stuff with proxy objects, debugging, etc.

So that's a sampling of some of the stuff you can do if you are not required to satisfy a type checker. The limitations are not imposed by static types, but by enforced static type checking.

4
  • 2
    "A Python 2 static type checker would reject the Python 3 code (and vice versa), even though it would never be executed. My type safe program contains a static type error." Sounds like what you really need there is some kind of "static if", where the compiler / interpreter doesn't even see the code if the condition is false. Commented Oct 26, 2012 at 2:09
  • @davidstone That exists in c++
    – Milind R
    Commented Dec 1, 2014 at 18:19
  • A Python 2 static type checker would reject the Python 3 code (and vice versa), even though it would never be executed. My type safe program contains a static type error. In any reasonable static language, you can do this with an IFDEF type preprocessor statement, while maintaining type safety in both cases. Commented Dec 8, 2014 at 15:12
  • 1
    @MasonWheeler, davidstone No, preprocessor tricks and static_if are both too static. In my example I used Python2 and Python3, but it could just have easily as been AmazingModule2.0 and AmazingModule3.0, where some interface changed between versions. The earliest that you can know the interface is at module import time, which is necessarily at runtime (at least if you have any desire to support dynamic linking). Commented Dec 13, 2014 at 12:30
18
votes

Duck-typed variables are the first thing everyone thinks of, but in most cases you can get the same benefits through static type inference.

But duck typing in dynamically-created collections is hard to achieve in any other way:

>>> d = JSON.parse(foo)
>>> d['bar'][3]
12
>>> d['baz']['qux']
'quux'

So, what type does JSON.parse return? A dictionary of arrays-of-integers-or-dictionaries-of-strings? No, even that isn't general enough.

JSON.parse has to return some kind of "variant value" that can be null, bool, float, string, array of any of these types recursively, or dictionary from string to any of these types recursively. The main strengths of dynamic typing come from having such variant types.

So far, this is a benefit of dynamic types, not of dynamically-typed languages. A decent static language can simulate any such type perfectly. (And even "bad" languages can often simulate them by breaking type safety under the hood and/or requiring clumsy access syntax.)

The advantage of dynamically-typed languages is that such types cannot be inferred by static type inference systems. You have to write the type explicitly. But in many such cases—including this once—the code to describe the type is exactly as complicated as the code to parse/construct the objects without describing the type, so that still isn't necessarily an advantage.

5
  • 21
    Your JSON parsing example can be easily handled statically by an Algebraic Data Type.
    – user39685
    Commented Oct 3, 2012 at 20:25
  • 2
    OK, my answer wasn't clear enough; thanks. That JSValue is an explicit definition of a dynamic type, exactly what I was talking about. It's those dynamic types that are useful, not languages that require dynamic typing. However, it's still relevant that dynamic types cannot be automatically generated by any real type inference system, while most of the common examples people are trivially inferrable. I hope the new version explains it better.
    – abarnert
    Commented Oct 3, 2012 at 20:37
  • 4
    @MattFenwick Algebraic Data Types are pretty much restricted to functional languages (in practice). What about languages like Java and c#?
    – spirc
    Commented Oct 5, 2012 at 6:25
  • 4
    ADTs exist in C/C++ as tagged unions. This isn't unique to functional languages. Commented Oct 5, 2012 at 13:39
  • 2
    @spirc you can emulate ADTs in a classical OO language using multiple classes that all derive from a common interface, run-time calls to getClass() or GetType(), and equality checks. Or you can use double dispatch, but I think that pays off more in C++. So you might have a JSObject interface, and JSString, JSNumber, JSHash, and JSArray classes. You would then need some code to turn this "untyped" data structure into an "application typed" data structure. But you would probably want to do this in a dynamically-typed language, too. Commented Oct 9, 2012 at 1:42
12
votes

As every remotely practical static type system is severely limited compared to the programming language it is concerned with, it cannot express all invariants which code could check at runtime. In order to not circumvent the guarantees a type system attempts to give, it hence opts to be conservative and disallow use cases which would pass these checks, but cannot (in the type system) be proven to.

I'll make an example. Suppose you implement a simple data model to describe data objects, collections of them, etc. which is statically typed in the sense that, if the model says the attribute x of object of type Foo holds an integer, it must always hold an integer. Because this is a runtime construct, you cannot type it statically. Suppose you store the data described in YAML files. You create a hash map (to be handed to a YAML library later), get the x attribute, store it in the map, get that other attribute which just so happens to be a string, ... hold a second? What's the type of the_map[some_key] now? Well shoot, we know that some_key is 'x' and the result hence must be an integer, but the type system can't even begin to reason about this.

Some actively researched type systems may work for this specific example, but these are exceedingly complicated (both for compiler writers to implement and for the programmer to reason in), especially for something this "simple" (I mean, I just explained it in one paragraph).

Of course, today's solution is boxing everything and then casting (or having a bunch of overriden methods, most of which raise "not implemented" exceptions). But this isn't statically typed, it's a hack around the type system to do the type checks at runtime.

7
  • Generic types don't have the boxing requirement. Commented Oct 3, 2012 at 20:47
  • @RobertHarvey Yes. I wasn't talking to the boxing in Java C#, I was talking about "wrap it up in some wrapper class whose sole purpose is representing a value of T in a subtype of U". Parametric polymorphism (what you call generic typing) however does not apply to my example. It's a compile-time abstraction over concrete types, but we need a runtime typing mechanism.
    – user7043
    Commented Oct 3, 2012 at 20:49
  • It may be worth to point out that the type system of Scala is Turing complete. So type systems can be less trivial than you picture.
    – Andrea
    Commented Oct 3, 2012 at 21:11
  • @Andrea I intentionally did not reduce my description to turing completeness. Ever programmed in a turing tarpit? Or tried to encode these things in types? At some point, it becomes far too complicated to be feasible.
    – user7043
    Commented Oct 4, 2012 at 12:59
  • @delnan I agree. I was just pointing out that type systems can do fairly complicated stuff. I had the impression that your answer meant that type system can only make trivial verification, but on a second read you did not write anything like this!
    – Andrea
    Commented Oct 4, 2012 at 14:12
7
votes

There is nothing you can do with dynamic typing that you can't do with static typing, because you can implement dynamic typing on top of a statically typed language.

A short example in Haskell:

data Data = DString String | DInt Int | DDouble Double

-- defining a '+' operator here, with explicit promotion behavior
DString a + DString b = DString (a ++ b)
DString a + DInt b = DString (a ++ show b)
DString a + DDouble b = DString (a ++ show b)
DInt a + DString b = DString (show a ++ b)
DInt a + DInt b = DInt (a + b)
DInt a + DDouble b = DDouble (fromIntegral a + b)
DDouble a + DString b = DString (show a ++ b)
DDouble a + DInt b = DDouble (a + fromIntegral b)
DDouble a + DDouble b = DDouble (a + b)

With enough cases you can implement any given dynamic type system.

Conversely, you can also translate any statically typed program into an equivalent dynamic one. Of course, you would lose all compile-time assurances of correctness that the statically typed language provides.

Edit: I wanted to keep this simple, but here are more details about an object model

A function takes a list of Data as arguments and performs calculations with side effects in ImplMonad, and returns a Data.

type Function = [Data] -> ImplMonad Data

DMember is either a member value or a function.

data DMember = DMemValue Data | DMemFunction Function

Extend Data to include Objects and Functions. Objects are lists of named members.

data Data = .... | DObject [(String, DMember)] | DFunction Function

These static types are sufficient to implement every dynamically typed object system I'm familiar with.

6
  • This is not the same at all because you can't add new types without revisiting the definition of Data.
    – Jed
    Commented Oct 5, 2012 at 12:53
  • 5
    You are mixing concepts of dynamic typing with weak typing in your example. Dynamic typing is about operating on unknown types, not defining a list of allowed types and overloading operations between those.
    – hcalves
    Commented Oct 5, 2012 at 14:52
  • 2
    @Jed Once you have implemented the object model, fundamental types, and primitive operations, no other groundwork is necessary. You can easily and automatically translate programs in the original dynamic language into this dialect. Commented Oct 5, 2012 at 15:30
  • 2
    @hcalves Since you're referring to overloading in my Haskell code I suspect you don't quite have the right idea about it's semantics. There I've defined a new + operator which combines two Data values into another Data value. Data represents the standard values in the dynamic type system. Commented Oct 5, 2012 at 15:35
  • 1
    @Jed: Most dynamic languages have a small set of "primitive" types and some inductive way to introduce new values (data structures like lists). Scheme, for example, gets quite far with little more than atoms, pairs and vectors. You should be able to implement these in the same way as the rest of the given dynamic type. Commented Oct 10, 2012 at 16:19
3
votes

Membranes:

A membrane is a wrapper around an entire object graph, as opposed to a wrapper for just a single object. Typically, the creator of a membrane starts out wrapping just a single object in a membrane. The key idea is that any object reference that crosses the membrane is itself transitively wrapped in the same membrane.

enter image description here

Each type is wrapped by a type that has the same interface, but which intercepts messages and wraps and unwraps values as they cross the membrane. What is the type of the wrap function in your favorite statically typed language? Maybe Haskell has a type for that functions, but most statically typed languages don't or they end up using Object → Object, effectively abdicating their responsibility as type-checkers.

4
  • 4
    Yes, Haskell can indeed to this using existential types. If you have some type class Foo, you can make a wrapper around any type instantiating that interface. class Foo a where ... data Wrapper = forall a. Foo a => Wrapper a Commented Oct 5, 2012 at 15:22
  • @JakeMcArthur, Thanks for explaining. That's yet another reason for me to sit down and learn Haskell. Commented Oct 5, 2012 at 18:27
  • 2
    Your membrane is an 'interface' and the types of the objects are "existentially typed" -- that is, we know they exist under the interface, but that's all we know. Existential types for data abstraction have been known since the 80s. A good ref is cs.cmu.edu/~rwh/plbook/book.pdf chapter 21.1 Commented Oct 5, 2012 at 19:27
  • @DonStewart. Are Java proxy classes an existential type mechanism then? One place where membranes become difficult is in languages with nominal type systems that have names for concrete types visible outside that type's definition. For example, one cannot wrap String since it is a concrete type in Java. Smalltalk does not have this problem because it does not attempt to type #doesNotUnderstand. Commented Oct 6, 2012 at 0:39
1
vote

As someone mentioned, in theory there is no much you can do with dynamic typing that you could not do with static typing if you would implement certain mechanisms on your own. Most of languages provide the type relaxation mechanisms to support type flexibility like void pointers, and root Object type or empty interface.

Better question is why is dynamic typing more suitable and more appropriate in certain situations and problems.

First, lets define

Entity - I would need a general notion of some entity in the code. It can be anything from primitive number to complex data.

Behavior - lets say our entity has some state and a set of methods that allow outside world to instruct the entity to certain reactions. Lets call the state + interface of this entity its behavior. One entity can have more than one behavior combined in a certain way by the tools language provides.

Definitions of entities and their behaviors - every language provides some means of abstractions which help you to define behaviors (set of methods + internal state) of certain entities in the program. You can assign a name to these behaviors and say that all instances that have this behavior are of certain type.

This is probably something that is not that unfamiliar. And as you said you understood the difference, but still. Probably not complete and most accurate explanation but I hope fun enough to bring some value :)

Static typing - behavior of all entities in your program are examined in compile time, before code is started to run. This means that if you want for example your entity of type Person to have behavior (to behave like) Magician then you would have to define entity MagicianPerson and give it behaviors of a magician like throwMagic(). If you in your code, mistakenly tell to ordinary Person.throwMagic() compiler will tell you "Error >>> hell, this Person has no this behavior, dunno throwing magics, no run!".

Dynamic typing - in dynamic typing environments available behaviors of entities are not checked until you really try to do something with certain entity. Running Ruby code that asks a Person.throwMagic() will not be caught until your code really comes there. This sounds frustrating, isn't it. But it sounds revelational as well. Based on this property you can do interesting things. Like, lets say you design a game where anything can turn to Magician and you don't really know who will that be, until you come to the certain point in code. And then Frog comes and you say HeyYouConcreteInstanceOfFrog.include Magic and from then on this Frog becomes one particular Frog that has Magic powers. Other Frogs, still not. You see, in static typing languages, you would have to define this relation by some standard mean of combination of behaviors (like interface implementation). In dynamic typing language, you can do that in runtime and nobody will care.

Most of dynamic typing languages have mechanisms to provide a generic behavior that will catch any message that is passed to their interface. For example Ruby method_missing and PHP __call if I remember good. That means that you can do any kind of interesting things in run time of the program and make type decision based on current program state. This brings tools for modeling of a problem that are lot more flexible than in, lets say, conservative static programming language like Java.

Not the answer you're looking for? Browse other questions tagged or ask your own question.