Typing In Python

What is Typing In Python

In Python, 'typing' refers to type annotations that specify the type of data that our code can handle. For example, whether a variable is an integer, a string, or perhaps a more complex data structure, like dictionary.

Typing is crucial because it clarifies what each part of your code is supposed to do, not just to you, but also to colleague who might work on your codebase.And It also acts as a form of documentation that's integrated directly into your code. A well-typed codebase is easier to debug and refactor. It's safer to change because you understand exactly what type of data each part of your code expects and produces.

In the provided function greeting, the parameter name is annotated with the type str, indicating that it is expected to be a string. The function performs a concatenation operation using the + operator between the literal string "Hello " and the parameter name. Since both operands are strings, Python supports this operation by returning another string as the result. The static type checker, such as mypy, uses this type annotation to verify that the types being used in operations like concatenation are compatible, and it understands that the output of the function is also a string, as indicated in the popup window.

A bit of historical context—typing was officially introduced in Python with version 3.5, through something known as PEP 484 in 2014

Use case of Typing (1)

Here we introduce two common and simple use cases of typing.
In this slide, we see how type annotations help prevent errors from the perspective of someone calling a function. When the function greeting is correctly called with a string "Andy", it matches the expected type. However, if a developer tries to pass an integer with greeting like 123 as the last image shown, the static type checker, such as the one integrated in VSCode, immediately flags this as an error. This alert helps developers catch type mismatches before the code is even run, ensuring that only appropriate types are used as arguments.Such early detection helps developers catch errors in the earliest phase of development, enhancing overall code quality and reducing debugging time.

Use case of Typing (2)

In the second example, we see how type annotations help prevent errors from fucntion creator perspective. In the first image, my_clever_function() explicitly specifiies its return type as string. But the return data is actually inferred as a boolean type. This mismatch between the annotated return type and the actual return type triggers a type error. This tell the developer that the function's implementation does not align with its annotated return type, indicating a potential bug.

In the second image, instead of annotate the return type explicitly, we can just let the static type checker to infer the return type for us, and then we can manually check if the inferred type meets our expectation.

Static type checker: MyPy and Pyright

In preivous slides, we told about the concept of "static type checker". This tool analyze the type annotation provided by developer, and try to find out the types of all variables as accurately as possible without running the code.

There are many static type checkers available in the python community, In this slide we will focus on two of the most popular ones, MyPy and Pyright.

Mypy is known for its strictness and tend to be more accurate in some rare case. And Pyright is developed by microsoft, and it is designed with performance as priority, making it suitable for large codebase.
Let compare the difference between these two static type checkers. In the case of speed, pyright is 3 to 5 times faster that mypy in typical use cases. In the case of strictness, Mypy tend to be stricter, which can help enforce a higher level of type safety. In the case of flexibility, Pyright offers advanced type inference capabilities and tends to be more forgiving with unannotated code, easing the developer's burden without sacrificing type safety.

Why choose Pyright over MyPy

In my personal experience, I prefer to use Pyright over MyPy. They both offer the same level of strictness, although MyPy is more accurate in some rare cases. However, it is extremely slow on large codebases. In my experience with a tax-risk-analysis project, we were using containers, so we had Docker Desktop running which put my PC under significant load. Each time I made a change to the code, it often took up to 10 seconds for MyPy to perform the check, whereas Pyright could always perform the check in real time. This kind of real-time type checking is important for developers to have a consistent development pace and not to be interrupted by lengthy MyPy checks.

Introduction to Stub Files(1/2)

In this part of our discussion, we'll explore what stub files are and how they contribute to Python typing. Stub files, with the .pyi extension, contain type annotations but no function bodies. This means they provide the necessary type information without including any actual code. These files are particularly valuable when dealing with external libraries or dynamically typed sections of code.

## Introduction to Stub Files(2/2)

Let's examine what happens when you don't have stub files and when you do. In the first scenario, without stub files for an untyped library like the msal library shown here, tools like Pyright do their best to infer types. However, as you can see in the example, without explicit type annotations, Pyright struggles to accurately determine the types and defaults to Unknown, which isn't very helpful for ensuring type safety.

In contrast, when stub files are available, Pyright uses the annotated types in these files, leading to much clearer and more accurate type inference. As shown in the second example, with a stub file, each parameter and the return type in the PublicClientApplication class are well-defined, which helps prevent many common errors in development by providing precise type checks.

Overloading Functions with Typing

Another feature brought with typing is the overload decorator. In Python, the return type of a function could be changed according to the type or the value of the passed arguments. With the overload decorator, we could notify the function caller of the return type given a set of arguments. In this example, the function will return a string if 'arg' is True, and return an integer if 'arg' is False. WIth overloading, function caller would know the return type for a given set of argument, making our function more predictable for user.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子了牛,更是在濱河造成了極大的恐慌屎飘,老刑警劉巖扯饶,帶你破解...
    沈念sama閱讀 216,591評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機铺韧,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來缓淹,“玉大人哈打,你說我怎么就攤上這事塔逃。” “怎么了料仗?”我有些...
    開封第一講書人閱讀 162,823評論 0 353
  • 文/不壞的土叔 我叫張陵湾盗,是天一觀的道長。 經(jīng)常有香客問我立轧,道長格粪,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,204評論 1 292
  • 正文 為了忘掉前任氛改,我火速辦了婚禮帐萎,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘平窘。我一直安慰自己吓肋,他們只是感情好凳怨,可當我...
    茶點故事閱讀 67,228評論 6 388
  • 文/花漫 我一把揭開白布瑰艘。 她就那樣靜靜地躺著,像睡著了一般肤舞。 火紅的嫁衣襯著肌膚如雪紫新。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,190評論 1 299
  • 那天李剖,我揣著相機與錄音芒率,去河邊找鬼。 笑死篙顺,一個胖子當著我的面吹牛偶芍,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播德玫,決...
    沈念sama閱讀 40,078評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼匪蟀,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了宰僧?” 一聲冷哼從身側(cè)響起材彪,我...
    開封第一講書人閱讀 38,923評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎琴儿,沒想到半個月后段化,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,334評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡造成,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,550評論 2 333
  • 正文 我和宋清朗相戀三年显熏,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片晒屎。...
    茶點故事閱讀 39,727評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡喘蟆,死狀恐怖现诀,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情履肃,我是刑警寧澤仔沿,帶...
    沈念sama閱讀 35,428評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站尺棋,受9級特大地震影響封锉,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜膘螟,卻給世界環(huán)境...
    茶點故事閱讀 41,022評論 3 326
  • 文/蒙蒙 一成福、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧荆残,春花似錦奴艾、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至俘闯,卻和暖如春潭苞,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背真朗。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評論 1 269
  • 我被黑心中介騙來泰國打工此疹, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人遮婶。 一個月前我還...
    沈念sama閱讀 47,734評論 2 368
  • 正文 我出身青樓蝗碎,卻偏偏與公主長得像,于是被迫代替她去往敵國和親旗扑。 傳聞我的和親對象是個殘疾皇子蹦骑,可洞房花燭夜當晚...
    茶點故事閱讀 44,619評論 2 354

推薦閱讀更多精彩內(nèi)容