Python 3 and static typing

后端 未结 5 1015
别那么骄傲
别那么骄傲 2020-12-12 11:34

I didn\'t really pay as much attention to Python 3\'s development as I would have liked, and only just noticed some interesting new syntax changes. Specifically from this SO

5条回答
  •  粉色の甜心
    2020-12-12 12:06

    "Static typing" in Python can only be implemented so that the type checking is done in run-time, which means it slows down the application. Therefore you don't want that as a generality. Instead you want some of your methods to check it's inputs. This can be easily done with plain asserts, or with decorators if you (mistakenly) think you need it a lot.

    There is also an alternative to static type checking, and that is to use an aspect oriented component architecture like The Zope Component Architecture. Instead of checking the type, you adapt it. So instead of:

    assert isinstance(theobject, myclass)
    

    you do this:

    theobject = IMyClass(theobject)
    

    If theobject already implements IMyClass nothing happens. If it doesn't, an adapter that wraps whatever theobject is to IMyClass will be looked up, and used instead of theobject. If no adapter is found, you get an error.

    This combined the dynamicism of Python with the desire to have a specific type in a specific way.

提交回复
热议问题