본문 바로가기
Python

[Python3] typing module

by llHoYall 2021. 7. 3.

We can use a type in Python3.

It is not enforced like other strong typed languages, but it can help us.

It can be a communication tool with other developers and can prevent mistakes.

Syntax

The default syntax is like this.

# def func_name(param: param_type) -> return_type
#     func_body

def say_hello(name: str) -> str:
    return f"Hello {name}"

Python3 supports bool, int, str, tuple, set, list, and dict.

typing Module

If you need a more specialized type, you can use typing module.

Union

It can have one of the types of Union.

from typing import Union

def test_func(id: Union[int, str]) -> None:
    print(id)

Any

It can have any type.

from typing import Any

def test_func(data: Any) -> None:
    print(data)

Tuple

It can have a typed tuple.

from typing import Tuple

def test_func(data: Tuple[str]) -> None:
    print(data)

Optional

It can have a specified type or None.

from typing import Optional

def test_func(age: Optional[int]) -> None:
    print(age)

Optional[int] is the same as Union[int, None].

Generic and TypeVar

We can make our own type using TypeVar.

It can be used like generic in other languages.

from typing import Generic, TypeVar

MyKey = TypeVar("MyKey")
MyData = TypeVar("MyData", str)

def test_func(key: Generic[MyKey], data: Generic[MyData]) -> None:
    print(key, data)

NewType

We can make a new type with the existing types.

from typing import NewType

UserId = NewType('UserId', int)
my_id = UserId(524313)

'Python' 카테고리의 다른 글

[Python] Running Python with Docker  (0) 2021.08.28
[PyQt6] Getting Started  (0) 2021.08.10
[Python] Decorator  (0) 2021.06.29
[Python] Draw shapes using tkinter  (0) 2021.05.29
[Python] itertools module  (0) 2021.05.15

댓글