如果函數註解(annotation)不能做參數限制,那他的用途是什麼? - Python

Posted by: Max Chen | in Python | 1 year, 1 month ago |

Python的函數的註解其實不會做任何處理,那註解到底有何用途呢?

首先我們來看一下,什麼叫做"註解不會做任何處理",例:

>>> def add(a : int,b : int) -> int: 
    return(a+b)

>>> add(1.5,1.2)
2.7

註:註解格式,如參數有預設值,擺在預設值之前

發現了嗎?僅管我們明明註解了a,b,return都是int,但仍然可以傳入float並回傳float,所以說函數的註解其實根本不會做任何處理,其實他就只是一個meta data,並儲存在 annotations(一個dict)中。

>>> add.__annotations__
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}

那註解到底有什麼用途呢?

其實也就是跟Python如何檢查函數的參數信息?或者獲取參數的信息呢? defaults 與__code__vs inspect - Python最後的結論很像,為什麼需要提取參數信息呢?

因為這樣一來(Bobo)框架就可以檢查傳入參數是否正確,而多了註解,(Bobo)框架甚至能夠在傳入參數前作預處理,將參數轉為正確的格式。

註:我們通常也使用inspect.sign.來獲取註解:

  • sig.return_annotation :獲取return註解

  • sig.parameters:是一個dict,每個param也有自己的annotation屬性。

比如,為add函數的參數a做預處理,如果非int,強制轉為int在餵入函數:

>>> input_a=1.5
>>> input_b=1.2
>>> if type(input_a) == sig.parameters['a'].annotation:
    add(input_a,b)
else:
    add(int(input_a),b)
>>> if type(input_a) == sig.parameters['a'].annotation:
    add(input_a,input_b)
else:
    add(int(input_a),input_b)

2.2 # 答案不是2.7,因為input_a被轉換為1了!

看看sig.parameters還有哪些屬性:

>>> from inspect import signature
>>> sig = signature(add)
>>> sig.return_annotation #獲取return註解
<class 'int'>
>>> for param in sig.parameters.values():
    #ljust : 返回一個原字符串左對齊,並使用空格填充至指定長度的新字符串。
    note = repr(param.annotation).ljust(13)
    print(note, ':', param.name, '=', param.default)

<class 'int'> : a = <class 'inspect._empty'>
<class 'int'> : b = <class 'inspect._empty'>

Reference:

https://www.books.com.tw/products/0010706172

Currently unrated
 or 

Subscribe

* indicates required

Recent Posts

Archive

2023
2022
2021

Categories

Apache 1

Data Science 2

Dbfit 1

Design Pattern 1

Devops 4

DigitalOcean 1

Django 1

English 3

Excel 5

FUN 4

Flask 3

Git 1

HackMD 1

Heroku 1

Html/Css 1

Linux 4

MDX 1

Machine Learning 2

Manufacture 1

Master Data Service 1

Mezzanine 18

Oracle 1

Postgresql 7

PowerBI 4

Powershell 4

Python 22

SEO 2

SQL Server 53

SQL Server Analytics Service 1

SQLite 1

Windows 1

database 8

work-experience 1

其他 1

投資入門 1

投資心得 2

時間管理 1

總體經濟 2

自我成長 3

資料工程 1

Tags

SEO(1) Github(2) Title Tag(2) ML(1) 李宏毅(1) SQL Server(18) Tempdb(1) SSMS(1) Windows(1) 自我成長(2) Excel(1) python Flask(1) python(5) Flask(2)

Authors

Max Chen (159)

Feeds

RSS / Atom

如果函數註解(annotation)不能做參數限制,那他的用途是什麼? - Python

© COPYRIGHT 2011-2022. Max的文藝復興. ALL RIGHT RESERVED.