Take the 2-minute tour ×



share|improve this question
show 11 more comments


migrated from stackoverflow.com Oct 3 '12 at 20:05

This question came from our site for professional and enthusiast programmers.

16 Answers










share|improve this answer
show 10 more comments







if sys.version_info[0] == 2:




Here's one more limitation:






share|improve this answer
show 1 more comment



>>> d = JSON.parse(foo)
>>> d['bar'][3]





share|improve this answer
Your JSON parsing example can be easily handled statically by an Algebraic Data Type. –  Matt Fenwick Oct 3 '12 at 20:25
add comment





share|improve this answer
show 7 more comments


A short example in Haskell:

data Data = DString String | DInt Int | DDouble Double

DInt a + DString b = (show a ++ b)
DInt a + DInt b = DInt (a + b)
DDouble a + DDouble b = DDouble (a + b)

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




type Function = [Data] -> ImplMonad Data

DMember is either a member value or a function.

data DMember = DMemValue Data | DMemFunction Function




share|improve this answer
show 2 more comments



enter image description here


share|improve this answer
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 –  Don Stewart Oct 5 '12 at 19:27
show 2 more comments



First, lets define








share|improve this answer
add comment

I ran into an example recently, as part of implementing tasks in ActionScript 3. AS3 has no generics (sortof) so it's easy to accidentally end up in situations where you have a task containing a task containing an int (doubly-nested) but mistakenly believe you have a task containing an int (singly-nested).

One way that I could avoid this problem is implementing a function "UnwrapUntilSinglyNested" that takes any task nested to any amount and outputs the intuitively equivalent singly-nested task. The type of this function, which is something like Task<T>|Task<Task<T>>|Task<Task<Task<T>>>|... -> Task<T>, is not expressible in "typical" type systems (like C/C#/Java, but not Haskell/Coq). (On the other hand it wouldn't be necessary in typical type systems because the mistake is caught by the compiler.)

share|improve this answer
recursive data types –  Matt Fenwick Oct 5 '12 at 12:10
show 1 more comment

In a statically typed language where types are either stated in the source - manifestly typed, or if the compiler infers types to some degree, could you theoretically write a function/procedure/class/method/... that could take valid source for that language then compile and evaluate it returning the result? If so, could you express the type of the result, or could the compiler infer the result?

What if you fed such a routine its own source, would it work then?

Would you have to make use of the hack that some statically typed languages have of effectively saying "don't check the type of that value please" to its type system?

Sometimes type expressions can be horrendously complex and we adapt the way we program to compensate. Dynamically typed languages have a different set of concerns that moulds the way their practitioners approach problems and the problems they choose to address. Eval/exec statements or functions are usually already available as part of the dynamic language as they carry around their own interpreter. Of course these statements are not a panacea, but I bring it up as a case where statically typed languages are at a disadvantage compared to dynamically typed languages. Saying that, it is good to see people adding local run-time type checking to predominantly statically typed languages and vice-versa, although there doesn't seem to be a happy medium in language design allowing the flexibility of typing that I would like available at the moment.

share|improve this answer
show 2 more comments

Readability and flexibility are small advantages? The early stages of software development are all about the latter, the late stages depend heavily on the former. It takes someone truly ignorant to say it's unimportant to have readable code.

As for cases where dynamic typing wins...

  • returning context-sensitive data like error strings / data arrays from the same function (as one argument, with no extra work required)
  • simple dynamic polymorphism (without defining and setting up functors etc.)
  • automatic conversions between equivalent data (includes simplified print-debugging), not limited to data->string conversions
  • free metadata storages everywhere (only in languages with dictionary variable types; something like: someObject["newProp1"]="mydata")
  • ability to avoid explicity defining all data structures (makes prototyping faster; example in PHP: return (object) array('count'=>5,'data'=>'hello');)

Consider this case:

data = load_something();
if( typeof( data ) == "string" ) // all this could actually be moved to "process" function
    print( data );
    print( process( data ) );

Now let's rewrite this in some statically typed language:

// none of the code that deals with data management is even displayed here...
var dataLoader = new SomeDataLoader(...); // this class is defined somewhere
LoadedData data;                          // this class is defined somewhere
if( !dataLoader.Load( &data ) )           // error string is stored internally and will be overwritten later
    print( dataLoader.GetLastError() );
    process( &data );
share|improve this answer
@MattFenwick You could've just said so. Anyway... I said "dynamic typing wins" not "impossible in static typing" - as it was noted in another answer, nothing is impossible. This is more related to something being natural to a language. Best tools for the job etc. That said, I'll try to find some time to add more examples. As for being rude - I don't see how it's rude to say things as they are. Also, there is no bias towards static typing; I didn't mention the good things about it because it's not what the question was about. For the record, I regularly use both kinds of languages myself. –  snake5 Oct 5 '12 at 12:49
show 6 more comments

One example I can think of I have never seen supported in any statically typed languages is the return type of a function. I can do this in python for example:

def foo(x):
    if x == 1:
      return MyClass()
    elif x == 2:
      return []
    return 7

In this trivial example it is next to worthless, but in python you can essentially override class construction with metaclass to return different types of classes based on some criteria, see here http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python for a better explanation of that.


Another example of this, easier to understand than the metaclass, is the eval function in python. It takes a string and returns a value. You have no idea ahead of time, what type that value will be. This is not possible in a statically typed language.

share|improve this answer
That function could be described as returning type MyClass | list | int. Whether that's a useful type or not is another question, but it's closely related to the question of whether this is a useful function, and of how it's used. –  abarnert Oct 3 '12 at 21:23
@grieve: I understand why you make the distinction, but from a type-theoretical point of view, there is no difference between a function that returns one of three possible types and a function that returns a value of an algebraic data type with three data constructors. You say that you have never seen this feature in any statically typed language, but the point of abarnert's comment is that it is perfectly possible to do exactly this in almost any statically-typed functional language. So this feature, while useful, has nothing to do with whether the language is statically or dynamically typed. –  Daniel Pryden Oct 3 '12 at 23:49
@DanielPryden: its not clear that eval is not possible for a typed language. Its an open problem. –  Jonathan Fischoff Oct 5 '12 at 23:29
show 7 more comments

There's very little practical things you can do in a dynamically typed language that can't be catered for under a particular static type system. But there are many different static type systems, and each have their own strengths and weaknesses. There will always be something you can do under static type system x that you can't do under static type system y. You can see this by looking at the other answers to this question; 'you can do that in type system z', but you can't do it in another.

With a dynamic type system, you can do pretty much all of it, oftentimes with a lot less ceremony. You're not constrained by how the type system fits together and what rules it has that allow you to do one cool thing but not another.

share|improve this answer
add comment

You can build all you want in both. But your way of programming will be vastly different.

Static type mean that you have contracts. So you have some kind of errors already wiped out, because you won't compile the other way. Globally, you know who you are calling this method of an objet of this class.

In dynamic typing, commonly called duck typing, you care less about the class of your object. You care about the "message" it can send. You just care he got the method you call.

You can partially do this in static type langage thanks to polymorphism or interfaces. The difference is mostly that, you don't program the same way. So both way have some merits and drawbacks.

Dynamic langages usually focus more on what you do than how you do this. So the intent of the programmer is clearer, but it can leads to pretty annoying bugs or an harder understanding of how the programme really work.

Globally, it is a bit easier to abstract things in dynamic langages than in static types, but it comes at the cost of slower code.

Understand, you achieve the same things, maybe even the same way (thanks to var, or dynamic types in static, polymorphism, interface, ...).

Dynamic typing offer more elegant code ..... or ugyier code, depending on the programmer. In static typing, there is less magic, and often one true way. So your code won't be as elegant than a good dnamic typing code, but you will see way less horrors.

A good comparison is java versus ruby. Java offer one true way, static typing, fast langage, but is ugly to some people, because you are bothered with trivial questions about types, contracts, ect .... Code is less beautiful, but interns are also restricted in the horrors they may produce.

Ruby on the other way, is known as elegant, slow ( no longer that true, same order than php and python, now), you have many ways to do things. So an expert may produce so pretty art, elegant and readable code, in wa fewer lines, withouth bother the reader with trivial questions about types. But you are also free to produce the uglyier code ever wrote, that nobody including yourself can understand.

In dynamic typing, you have more fredom, some may say more power, more productivity, but this comes at a price. You have to be self-disciplined, and you will suffer from the horrors wrote by a noob.

So no style is really superior to the other.

share|improve this answer
“dynamic typing, commonly called duck typing” – wrong, wrong, wrong. Two totally different things. –  Konrad Rudolph Oct 5 '12 at 14:31
show 3 more comments

Dynamic typing allows you to keep objects of different classes (that have nothing to do with one another) together in single collection without additional layer of indirection.

That's what really bite me when I move from dynamic typing to static typing. Suddenly collections become complex thing.

share|improve this answer
add comment

Typing is often times a mechanism for creation of methods. If you can defer creation of the type until runtime, you can (in theory, not necessary in Python, but in dynamic languages that would allow this), to create a method that specializes on a type that did not exist in your program, once you compiled it.

When this may be helpful? In certain cases there are just too many types, but the user will never use all of them. Somewhat artificial example: say, you have a program that allows you to query your database which contains 100 tables, each table has 10 columns. Theoretically, you can create C(100 * 10, 100) types of objects by querying your database - if you wanted to do object mapping at compile time - that would be not only your own life time work, but not even your grand children would have finished it. Deferring type creation to runtime allows you to create only the necessary types in your program. And, voila, C# can do it too (sort of). This is also very similar to how V8 implementation of JavaScript works behind the scenes (it creates strongly typed objects, from dynamically created types, not just string hashes), etc. etc. There may be plenty of valid uses.

PS. you can also think of a property access operator as being one such method, to make this more generic.

share|improve this answer
Your first paragraph reads very confused. While dynamic typing allows naturally treating types as first class objects, this is neither necessarily the case nor the point of the exercise. I also don't know how you arrive at 100^10 types. And the note about V8 misrepresents things -- while V8 specializes for object layouts via maps, this is a mere implementation detail and it's solely about in-memory object layout, not about anything resembling a "type" by the common definitions. –  delnan Oct 3 '12 at 20:43
@wvxvw: Incorrect. Anonymous types are generated at compile time. See Anonymous Types (C# Programming Guide): "Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type name is generated by the compiler and is not available at the source code level." You can even use a decompiler to open the generated assembly and see the anonymous classes that were generated. –  Allon Guralnek Oct 7 '12 at 11:37
@wvxvw: The article is completely irrelevant to the topic at hand. dynamic and DynamicObject provides dynamic binding, not dynamic typing! At no point has any type been created at runtime. And of course you talked about anonymous types - your example talked about querying the database with an arbitrary projection plus object mapping, which with .NET involves anonymous types. Example: from c in db.Customers select new { c.FirstName, c.City }. –  Allon Guralnek Oct 7 '12 at 13:38
show 6 more comments

how about:

def adder(x, y):
    return x+y

[0, 1, 2, 0, 1, 2, 3, 4]

See all the flexibility?

share|improve this answer
-1 That's just polymorphism. –  delnan Oct 3 '12 at 20:10
@Justin984 If you can't do this in your statically typed language of choice, that language's type system sucks or you don't understand how to utilize it. Heck, even Java could do it if it had operator overloading, or allowed add interface implementations for types we didn't define. –  delnan Oct 3 '12 at 20:14
@Justin984 The solutions I refer to all only need a single implementation. So do solutions involving parametric polymorphism (e.g. in Haskell, where we can do this easily). –  delnan Oct 3 '12 at 20:19
This answer is totally wrong and misleading. –  Matt Fenwick Oct 3 '12 at 20:22
@Justin984 No types are being inferred here. Type inference has nothing to do with static/dynamic typing. For example, Haskell is as statically typed as it gets, and infers a static type for the function here (written adder x y = x + y, full stop) without any type annotations. –  delnan Oct 3 '12 at 20:25
show 5 more comments

Your Answer


