mypy

How to get Mypy to realize that sorting two ints gives back two ints

人走茶凉 提交于 2020-06-17 01:57:32
问题 My code is as follows: from typing import Tuple a: Tuple[int, int] = tuple(sorted([1, 3])) Mypy tells me: Incompatible types in assignment (expression has type "Tuple[int, ...]", variable has type "Tuple[int, int]") What am I doing wrong? Why can't Mypy figure out that the sorted tuple will give back exactly two integers? 回答1: The call to sorted produces a List[int] which carries no information about length. As such, producing a tuple from it also has no information about the length. The

Can you specify variance in a Python type annotation?

怎甘沉沦 提交于 2020-06-16 07:07:46
问题 Can you spot the error in the code below? Mypy can't. from typing import Dict, Any def add_items(d: Dict[str, Any]) -> None: d['foo'] = 5 d: Dict[str, str] = {} add_items(d) for key, value in d.items(): print(f"{repr(key)}: {repr(value.lower())}") Python spots the error, of course, helpfully informing us that 'int' object has no attribute 'lower' . Too bad it can't tell us this until run time. As far as I can tell, mypy doesn't catch this error because it allows arguments to the d parameter

Can you specify variance in a Python type annotation?

a 夏天 提交于 2020-06-16 07:07:18
问题 Can you spot the error in the code below? Mypy can't. from typing import Dict, Any def add_items(d: Dict[str, Any]) -> None: d['foo'] = 5 d: Dict[str, str] = {} add_items(d) for key, value in d.items(): print(f"{repr(key)}: {repr(value.lower())}") Python spots the error, of course, helpfully informing us that 'int' object has no attribute 'lower' . Too bad it can't tell us this until run time. As far as I can tell, mypy doesn't catch this error because it allows arguments to the d parameter

MyPy doesn't allow constrained TypeVar's to be covariant? Defining a generic dict with constrained but covariant key-val types

隐身守侯 提交于 2020-05-12 04:48:48
问题 I'm trying to define a custom generic dict, whose keys are of type T_key and values are of type T_val . I also want to put constraints on T_key and T_val , such that T_key can only be of type A or B or their subclass. How do I accomplish this? from typing import TypeVar, Generic class A: ... class B: ... class Asub(A): ... class Bsub(B): ... T_key = TypeVar('T_key', A, B, covariant=True) T_val = TypeVar('T_val', A, B, covariant=True) class MyDict(Generic[T_key, T_val]): ... w: MyDict[ A, B] x

MyPy doesn't allow constrained TypeVar's to be covariant? Defining a generic dict with constrained but covariant key-val types

China☆狼群 提交于 2020-05-12 04:47:18
问题 I'm trying to define a custom generic dict, whose keys are of type T_key and values are of type T_val . I also want to put constraints on T_key and T_val , such that T_key can only be of type A or B or their subclass. How do I accomplish this? from typing import TypeVar, Generic class A: ... class B: ... class Asub(A): ... class Bsub(B): ... T_key = TypeVar('T_key', A, B, covariant=True) T_val = TypeVar('T_val', A, B, covariant=True) class MyDict(Generic[T_key, T_val]): ... w: MyDict[ A, B] x

Incompatible types when assigning an empty tuple to a specialised variable

感情迁移 提交于 2020-05-09 03:30:08
问题 I have a variable path , which should be a tuple of strings. I want to start with it set to an empty tuple, but mypy complains. path: Tuple[str] = () The error is: Incompatible types in assignment (expression has type "Tuple[]", variable has type "Tuple[str]") How can I assign an empty tuple to a typed variable? Motivation The reason I want to do this is: I want to build up the tuple dynamically, and tuples (unlike lists) can be used as dictionary keys. For example (not what I'm actually

全面理解Python中的类型提示(Type Hints)

笑着哭i 提交于 2020-05-06 10:53:02
众所周知,Python 是动态类型语言,运行时不需要指定变量类型。这一点是不会改变的,但是2015年9月创始人 Guido van Rossum 在 Python 3.5 引入了一个类型系统,允许开发者指定变量类型。它的主要作用是方便开发,供IDE 和各种开发工具使用,对代码运行不产生影响,运行时会过滤类型信息。 Python的主要卖点之一就是它是动态类型的,这一点也不会改变。而在2014年9月, Guido van Rossum (Python BDFL ) 创建了一个Python增强提议( PEP-484 ),为Python添加类型提示(Type Hints)。并在一年后,于2015年9月作为Python3.5.0的一部分发布了。于是对于 存在了二十五年 的Python,有了一种标准方法向代码中添加类型信息。在这篇博文中,我将探讨这个系统是如何成熟的,我们如何使用它以及类型提示的下一步是什么。 为什么需要类型提示? 类型提示的优点 首先,让我们看看为什么需要Python中的类型提示(Type Hints)。类型提示有很多优点,我将尝试按重要性顺序来列举这些优点: 易于理解代码 了解参数的类型,可以使得理解和维护代码库变得更加容易。 例如,现在有一个函数。虽然我们在创建函数时知道了参数类型,但几个月之后就不再是这种情况了。 在代码旁边陈述了所有参数的类型和返回类型

Type hints when representing dict keys by attribute notation in python 3.6

二次信任 提交于 2020-03-22 13:38:53
问题 Given the example of the first answer in Accessing dict keys like an attribute?: class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self and a function that returns: def dict_to_attrdict(somedict): return AttrDict(**somedict) assigned as: data = dict_to_attrdict(mydict) What is the correct way to add type hints for the class and function that will pass mypy checking given the following constraints: the dict keys will

Type hints when representing dict keys by attribute notation in python 3.6

不想你离开。 提交于 2020-03-22 13:36:45
问题 Given the example of the first answer in Accessing dict keys like an attribute?: class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self and a function that returns: def dict_to_attrdict(somedict): return AttrDict(**somedict) assigned as: data = dict_to_attrdict(mydict) What is the correct way to add type hints for the class and function that will pass mypy checking given the following constraints: the dict keys will

python lib

二次信任 提交于 2020-03-17 12:10:25
某厂面试归来,发现自己落伍了!>>> 7 essential PyPI libraries and how to use them Solve common Python problems by learning how to use these seven Python Package Index (PyPI) libraries. 7_essential_pypl_libraries-cover.jpg Download guide to 7 essential PyPI libraries Python is one of the most popular programming languages in use today—and for good reasons: it's open source, it has a wide range of uses (such as web programming, business applications, games, scientific programming, and much more), and it has a vibrant and dedicated community supporting it. In this guide, we'll look at seven Python Package Index