[PYTHON] Limitation of default dict using typing

Introduction

There is an official document of default dict using typing.

However, how to use it is not explained in detail, so I will summarize it.

defualtdict

defaultdict specifies callable and one that returns a value. For example:

from collections import defaultdict

d1 = defaultdict(int)
d2 = defaultdict(lambda: 'hello')

Since int is Callable, it can be specified. And if there is no Key, these Callables will be called and will be the initial values.

Therefore, if you set d1 ['hello'], int () will be executed and 0 will be entered if Key does not exist at this point.

defaultdict using typing

For defaultdict, Callable on the Value side can be specified, but there are no restrictions on Key. Therefore, the Key should be designed to take only str! Even if the engineer thinks, that thought probably does not reach the IDE.

Therefore, typing is used.

from collections import defaultdict
from typing import  DefaultDict

dic: DefaultDict[str, int] = defaultdict(int)
dic['hoge'] = 10
dic['huga']

# defaultdict(<class 'int'>, {'hoge': 10, 'huga': 0}
print(dic)

By specifying the type like DefaultDict [key, value], you can limit the type taken by key and the type taken by value. Therefore, if you write as follows, you should be careful from the IDE that the instance of A will be included in the initial value even though the type of int should be taken as Value. (It will be easier to receive type support, I'm happy.)

from collections import defaultdict
from typing import DefaultDict


class A:
    pass


dic: DefaultDict[str, int] = defaultdict(lambda: A())

Recommended Posts

Limitation of default dict using typing
Example of using lambda
Implementation of TF-IDF using gensim
python: Basics of using scikit-learn ①
Introduction of caffe using pyenv
A memorandum of using eigen3