Friday, May 13, 2016

Dynamic Typing vs Static Typing & Strongly typed vs. Weakly typed

In a dynamically typed language, a variable is simply a value bound to a name; the value has a type -- like "integer" or "string" or "list" -- but the variable itself doesn't. You could have a variable which, right now, holds a number, and later assign a string to it if you need it to change.

In a statically typed language, the variable itself has a type; if you have a variable that's an integer, you won't be able to assign any other type of value to it later. Some statically typed languages require you to write out the types of all your variables, while others will deduce many of them for you automatically. A statically typed language can catch some errors in your program before it even runs, by analyzing the types of your variables and the ways they're being used. A dynamically language can't necessarily do this, but generally you'll be writing unit tests for your code either way (since type errors are a small fraction of all the things that might go wrong in a program); as a result, programmers in dynamic languages rely on their test suites to catch these and all other errors, rather than using a dedicated type-checking compiler.

In a strongly typed language, you are simply not allowed to do anything that's incompatible with the type of data you're working with. For example, in a weakly typed language you can typically do 3 + 5 + 7 and get the result 15, because numbers can be added; similarly, you can often do 'Hello' + 'And' + 'Goodbye' and get the result "HelloAndGoodBye", because strings support concatenation. But in a strongly-typed language you can't do 'Hello' + 5 + 'Goodbye', because there's no defined way to "add" strings and numbers to each other. In a weakly typed language, the compiler or interpreter can perform behind-the-scenes conversions to make these types of operations work; for example, a weakly typed language might give you the string "Hello5Goodbye" as a result for 'Hello' + 5 + 'Goodbye'. The advantage to a strongly typed language is that you can trust what's going on: if you do something wrong, your program will generate a type error telling you where you went wrong, and you don't have to memorize a lot of arcane type-conversion rules or try to debug a situation where your variables have been silently changed without your knowledge.

Python is a strongly and dynamically typed programming language.

No comments:

Post a Comment