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
69 views
in Technique[技术] by (71.8m points)

python - Correctly naming variables types

For a project I have to use lists, tuples or even list of tuples (array of vertices for example) and so on. While writing methods, classes I want to specify the type of their variables. For example:

def Example_Method(self, name: str, age: int):
    return name + str(age)

or

class Example_Class:
    def __init__(self, cents: int):
        self.euros: float = cents / 100

With basic types it is all nice and clean, but how does one name list of floats, tuple of strings or even list of lists or list of tuples. Have searched for information, but couldn't find any or don't know how to name it correctly.

question from:https://stackoverflow.com/questions/65883489/correctly-naming-variables-types

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

1 Reply

0 votes
by (71.8m points)

For all this, there is the excellent typing library

In your case you could to

from typing import List, Tuple

and then you can type hint a variable by doing, for example,

age: List[float] = [28.2, 78.9, 40.5]
names: Tuple[str, str, str] = ('Simon', 'Alice', 'Bob')

and so on. The library is extremely flexible. For a dictionary, for example, it lets you specify the type of keys and values separately as well. If you read the documentation it will show you how to type hint even very complex stuff. It's worth noting that as of Python 3.9, most of the functionalities of this library have been incorporated into the python syntax. So unless you need the typing library for complex cases (e.g. you need to type hint a Callable, i.e. a function, or you need to specify multiple possible types using Union etc.) you can just type hint things in python, so the examples above would become:

age: list[float] = [28.2, 78.9, 40.5]
names: tuple[str, str, str] = ('Simon', 'Alice', 'Bob')

without you needing to import any library. You still need the typing library for Python 3.8 and below.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

57.0k users

...