Strong typing implementation for Python

John Michael Lafayette johnmichaelreedfas at gmail.com
Fri Oct 9 12:26:17 EDT 2015


I would like Python to have a strong typing feature that can co-exist with
the current dynamic typing system. Currently Python is like this:

    var animal = Factory.make("dog")  # okay.
    var dog = Factory.make("dog")       # okay.
    var cat = Factory.make("dog")        # are you sure?

I would like Python to also be able to also do this:

    Animal a = Factory.make("dog")    # okay. Dog is Animal.
    Dog d = Factory.make("dog")         # okay. Dog is Dog.
    Cat c = Factory.make("cat")           # Runtime error. Dog is not Cat.

With a strong typing option that performs runtime type checking, the reader
can be certain that the program is running the type they expect. Also, the
IDE can be more helpful. Example:

    var dog = Factory.make("dog")  # okay
    dog. (Ctr+Space)                       # Auto-complete lists only
Animal methods.

    Dog d = Factory.make("dog")     # okay. Dog is dog.
    d. (Ctr+Space)                            # Auto-complete lists methods
for Dog and Animal.

In C++, this could be implemented by using dynamic_cast or typeinfo /
typeid. The interpreter look for an uppercase word followed by a lowercase
word followed by "=" and then it check the type on the right side of the
"=" at runtime and see if it is an instance of the (uppercase) type on the
left side of the "=". If not, the interpreter throws a runtime error that
says something like "Type Dog is not instance of type Cat. Line: 45".

This feature can be completely optional and could be integrated without
anyone noticing. If it is integrated, only the people who want this type
safety would have to use it. If there is a performance penalty, it would
mainly affect the people who use this feature. Given that a lot of people
transition from C/C++/Java to Python, I think that this feature would be
intuitive to many users and a good addition for people who like type safety.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20151009/a0d34cc1/attachment.html>


More information about the Python-list mailing list