You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

136 lines
3.9 KiB
Plaintext

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

{
"cells": [
{
"cell_type": "markdown",
"id": "6da43522",
"metadata": {},
"source": [
"# Aннотация типов #"
]
},
{
"cell_type": "markdown",
"id": "a086d5d9",
"metadata": {},
"source": [
"В Python'е последних версий появилась возможность аннотировать типы, и делается это с помощью двоеточия в случае параметров, и вот такой вот стрелочкой, если мы хотим указать, какого типа возвращаемое значение должно вернуться из функции."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "2ae84c77",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"21\n",
"One, two\n"
]
}
],
"source": [
"def add(x: int, y: int) -> int:\n",
" s: int = x + y\n",
" return s\n",
"\n",
"print(add(10, 11))\n",
"print(add(\"One, \", \"two\"))"
]
},
{
"cell_type": "markdown",
"id": "80d0226a",
"metadata": {},
"source": [
"Однако, что интересно, если мы передадим даже параметры других типов, как в данном случае, то у нас код все равно исполняется, потому что Python - это динамический язык, и аннотация типов призвана помочь программисту или его `IDE` отловить какие-то ошибки.\n",
"\n",
"Тем не менее код все равно исполняется. Если вы считаете это необходимым, можете использовать аннотацию типов, а так же изучить пакет `typing` и `mypy`.\n",
"\n",
"Рекомендую еще использовать аннотацию типов в кавычках, что может Вас огородить от ряда проблем с цеклическими импортами."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "9c6913fa",
"metadata": {},
"outputs": [],
"source": [
"from typing import TYPE_CHECKING\n",
"\n",
"if TYPE_CHECKING:\n",
" from typing import List\n",
"\n",
"def to_list(x: \"int\", y: \"int\") -> \"List[int]\":\n",
" return [x, y]"
]
},
{
"cell_type": "markdown",
"id": "1cc049a2",
"metadata": {},
"source": [
"Aннотацию типов можно производить с помощью комментариев."
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "d9133920",
"metadata": {},
"outputs": [],
"source": [
"from typing import TYPE_CHECKING\n",
"\n",
"if TYPE_CHECKING:\n",
" from typing import List\n",
"\n",
"def to_list(x, y):\n",
" # type: (int, int) -> List[int]\n",
" \n",
" result = [x, y] # type: List[int]\n",
" \n",
" return result"
]
},
{
"cell_type": "markdown",
"id": "a01ed930",
"metadata": {},
"source": [
"Aннотацию типов можно производить в отдельном файле с расширением `.pyi`\n",
"\n",
"```python\n",
"from typing import List\n",
"\n",
"def to_list(x: \"int\", y: \"int\") -> \"List[int]\": ...\n",
"```"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.8"
}
},
"nbformat": 4,
"nbformat_minor": 5
}