How to perform type checking with the typing Python module?

前端 未结 2 413
心在旅途
心在旅途 2020-12-09 05:57

I am reading the typing module code and also looking into mypy to understand how it does type checking. Unfortunately for me, mypy builds a very smart tree with

相关标签:
2条回答
  • 2020-12-09 06:27

    The library Pyadaaah offers automatic runtime (resp. dynamic) type and range checking as well as signals for class attributes.

    E.g. have a look at the belonging youtube video (series) starting with this: https://www.youtube.com/watch?v=Y3Hmg_HQtsY

    Which, by the way, also is a quite nice introduction to the (underlying) property/getter/setter mechanism as well.

    Pyadaaah does not use the typing library though.

    0 讨论(0)
  • 2020-12-09 06:30

    You can easily get the very limited functionality that works correctly for the simple examples provided in your question:

    import mypy.api
    
    def check_type(value, typ):
        program_text = 'from typing import *; v: {} = {}'.format(typ, repr(value))
        normal_report, error_report, exit_code = mypy.api.run(['-c', program_text])
        return exit_code == 0
    
    int_ = 1
    str_ = 'a'
    list_str_ = ['a']
    list_int_ = [1]
    tuple_int_ = (1,)
    
    assert check_type(int_, 'int')
    assert not check_type(str_, 'int')
    assert check_type(list_int_, 'List[int]')
    assert not check_type(list_str_, 'List[int]')
    assert check_type(list_int_, 'List[Any]')
    assert check_type(tuple_int_, 'Tuple[int]')
    

    You can even do some more advanced stuff (for example, refer to the types that correspond to classes you defined in your program) by extending this code a bit, so that mypy gets to parse your entire source code as opposed to just the current line.

    Alternatively, you might want to look at enforce or typeguard.

    0 讨论(0)
提交回复
热议问题