Python: type checking decorator

风格不统一 提交于 2019-12-06 02:21:07

I would actually discourage to typecheck input variables. Performance aside, Python is a dynamically typed language and in some cases (testing, for instance) you would need to pass an object that implement some attributes of the object you initially planned to encourted and, that will work fine with your code.

A simple example:

class fake_str:
    def __init__(self, string):
        self.string = string

    def __str__(self):
        return self.string

string = fake_str('test')

isinstance(string, str) # False
string # 'test'

Why would you not accept something that is working ?

Just allow compatible objects to work with your code.

Easier to ask for forgiveness than permission !

If you want type checking use python 3.5 and its typing module which has support for built in type-hinting.

http://blog.jetbrains.com/pycharm/2015/11/python-3-5-type-hinting-in-pycharm-5/

EDIT:

As a warning to the reader. Type hinting in a language like python can be useful but is also a pain. Lots of python APIs are highly polymorphic, accepting many different types of different arguments and optional arguments. The type signatures on these functions are gnarly and annotating them is not helpful at all. But for simple functions that take and return simple types type hinting can only help improve clarity.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!