Is it possible to make python throw errors if the type of the argument passed to the annotated function doesn't match the one specified?

后端 未结 3 1641
没有蜡笔的小新
没有蜡笔的小新 2020-12-10 12:08

One of the new features in python3.5 is type hinting. For example the code below is valid now:

def greeting(name: str) -> str:
    return \'Hello \' + nam         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 12:21

    I think the simplest way is to check the type:

    def greeting(name):
        if not isintstance(name, str):
            raise TypeError('Expected str; got %s' % type(name).__name__)
        return 'Hello ' + name
    

提交回复
热议问题