Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

Python 3 dictionary with known keys typing

I'm using Python 3 typing feature for better autocomplete.

Many times I have functions that return key/value (dictionary) with specific keys. super simple example:

def get_info(name):
    name_first_letter = name[0]
    return {'my_name': name, 'first_letter': name_first_letter}

I want to add type hinting to this function to tell others who use this function what to expect.

I can do something like:

 class NameInfo(object):
     def __init__(self, name, first_letter):
         self.name = name
         self.first_letter = first_letter

and then change the function signature to:

def get_info(name) -> NameInfo:

But it requires too much code for each dictionary.

What is the best practice in that case?

question from:https://stackoverflow.com/questions/44225788/python-3-dictionary-with-known-keys-typing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As pointed out by Blckknght, you and Stanislav Ivanov in the comments, you can use NamedTuple:

from typing import NamedTuple


class NameInfo(NamedTuple):
    name: str
    first_letter: str


def get_info(name: str) -> NameInfo:
    return NameInfo(name=name, first_letter=name[0])

Starting from Python 3.8 you can use TypedDict which is more similar to what you want:

from typing import TypedDict


class NameInfo(TypedDict):
    name: str
    first_letter: str


def get_info(name: str) -> NameInfo:
    return {'name': name, 'first_letter': name[0]}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...