Static Typing in Python

Jacek Generowicz jacek.generowicz at cern.ch
Mon Mar 15 08:41:10 EST 2004


Peter Hickman <peter at semantico.com> writes:

> Premshree Pillai wrote:
> > Like in C, C++, etc, Python too is
> > strongly typed, i.e., variables are necessarily bound
> > to a particular type.
> 
> Python 1.5.2 (#1, Jan 31 2003, 11:01:49)  [GCC 2.96 20000731 (Red Hat
> Linux 7.2 2 on linux-i386
> 
> Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>  >>> a = 1
>  >>> a
> 1
>  >>> a = "fred"
>  >>> a
> 'fred'
>  >>> a = open
>  >>> a
> <built-in function open>
>  >>>
> 
> So here was have a variable 'a'. In the first instance I set it to a
> number. Then I set it to a string. Now in a strongly typed language,

Firstly, you are confusing static (as opposed to dynamic) type
systems, with strong (as opposed to weak) type systems.

The two concepts are completely orthogonal to eachother.

(Besides, "strong typing" and "weak typing" are not really
well-defined concepts.)

> such as C or C++, would be screaming that "fred" was not an integer.

Secondly, you appear to be confusing C and C++ with strongly typed
languages. A common mistake :-)

> Could you please clarify how this consitutes Python being 'strongly typed'?

Python is strongly typed because:

- lots of type checking is done
- few implicit type conversions are done.
- No operations which are inappropriate to the object(s) in question
  are allowed.

Try this ...

    #include <iostream>
    
    void foo() {}
    
    int main() {
    
    float fs[128];
    
    char c = 'a';
    // add integer to character
    c = c + 1;
    // Use a character to subscript an array
    std::cout << fs[c] << std::endl;
    // Out of bounds array access
    std::cout << fs[200] << std::endl;
  
    int* ip;
    ip = (int*)(void*)(&foo);
    // Add an integer to a function
    std::cout << 3+(*ip) << std::endl;
  
    return 0;
    }

So, here we have four examples of weak typing in C++:

- adding integers to characters is allowed.
- subscripting arrays with characters is allowed
- accessing non-existent elements of an array is allowed
- adding functions to integers is allowed

Try as you will, Python would not allow you to do any of these things,
because it is _strongly typed_ with respect to these operations on
these types.

(Yes, this does show that static type systems are rather liable to be
inherently less strong that dynamic ones, because _no runtime type
checking_ is done at all; compile time is your last defence against
type errors. With dynamic typing, you still have the opportunity to do
strong type checking at runtime.)



More information about the Python-list mailing list