Search code examples
pythontypesstrong-typing

python strong/weak dynamic/static type language?


l learned that Python is strong-dynamic typed language.
dynamic: type of a variable is determined at execution time NOT compiling time. For this part, I can understand that type is determined when a value(type of course) is assigned to the variable.

strong: you can NOT change the type of a variable. But this is not the real case:

>>> a = 1
>>> type(a)
<type 'int'>
>>> a = 's'
>>> type(a)
<type 'str'> 

From the code above, I can change the type of variable a from int to str.
How can this happen? Could I say Python is a weak-typed language?


EDIT:

If you can give me a code snippet that shows how strong-dynamic typing affect Python programming, I would appreciate it pretty much! During my usual coding, I never care about the strong-dynamic typing issues. It seldom affects my code function as well. Weird!


EDIT:
Conclusion from the answers:

  1. Only object/value has type attribute. Variable has no type.
  2. (Strong) Type determines what operations can be performed over/between objects/values (maybe variables referring to them).
  3. (Dynamic) Type means variable just a label (reference to object/value). This label can refer to any object/value of any type.

Solution

  • The key is that an object retains its type no matter what you do to it. An int is an int is an int; a str is a str; a float is a float. In a weakly typed language, you can do something like

    i = "1" 
    j = i + 2
    

    and get j == 3. In python, you get

    TypeError: cannot concatenate 'str' and 'int' objects
    

    A str is always a str, and can't be treated as an int even if the string contains a number.

    Try this:

    for a in {1, 'abc', 3.14159}:
        print a
        print type(a)
    

    which will produce

    3.14159
    <type 'float'>
    1
    <type 'int'>
    abc
    <type 'str'>
    

    A single variable can be set to refer to any type of object - that's the "dynamic" part of it. But the object is always of the same type no matter how you refer to it - that's the "strong" part of it.