Tools for static type checking in Python

前端 未结 7 2045
灰色年华
灰色年华 2020-12-01 09:00

I\'m working with a large existing Python codebase and would like to start adding in type annotations so I can get some level of static checking. I\'m imagining something l

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 09:42

    I had a similar need some time ago. All the existing solutions that I've found had some problem or does not have a feature that I'd like to have, so I've made my own.

    Here's how you use it:

    from requiretype import require
    
    @require(name=str, age=(int, float, long))
    def greet_person(name, age):
        print "Hello {0} ({1})".format(name, age)
    
    >>> greet_person("John", 42)
    Hello John (42)
    
    >>> greet_person("John", "Doe")
    # [...traceback...]
    TypeError: Doe is not a valid type.
    Valid types: , , 
    
    >>> greet_person(42, 43)
    # [...traceback...]
    TypeError: 42 is not a  type
    

    I hope this is useful for you.

    For more details look at:

    • https://pypi.python.org/pypi/RequireType
    • https://github.com/ivanalejandro0/RequireType

    P.S.: (quoting myself from github repo)

    For most cases I'd recommend using tests instead of type checking since it's more natural to do that in Python. But, there are some cases where you want/need to specify a specific type to use and since python does not have type checks for parameters here's where this is useful.

提交回复
热议问题