代码之家  ›  专栏  ›  技术社区  ›  Adam Matan

集合的正确mypy注释是什么。柜台

  •  0
  • Adam Matan  · 技术社区  · 3 年前

    我的问题

    我正在编写一个Python函数 Counter 它对字符串进行计数并打印计数的字符串总数。我试着用各种方式注释这个函数。但都没有通过mypy测试:

    密码

    from collections import Counter
    import typing
    
    def f1(c : Counter[str]) -> None:
        print(c.total())
    
    def f2(c : Counter) -> None:
        print(c.total())
    
    def f3(c : Counter[str, int]) -> None:
        print(c.total())
    
    
    c : Counter = Counter()
    c.update(['a', 'b', 'c', 'a', 'b', 'c'])
    
    f1(c)
    f2(c)
    f3(c)
    

    错误

    use_counter.py:5: error: "Counter[str]" has no attribute "total"
    use_counter.py:8: error: "Counter[Any]" has no attribute "total"
    use_counter.py:10: error: "Counter" expects 1 type argument, but 2 given
    use_counter.py:11: error: "Counter[Any]" has no attribute "total"
    

    我试过什么

    各种注释方式 Counter 在里面 f1 , f2 f3 )并在谷歌上搜索答案。

    我的问题

    注释的正确方法是什么 collections.Counter 因此其方法(如 total )被mypy认出了吗?

    0 回复  |  直到 3 年前