Python typing

From wikinotes
Revision as of 15:10, 3 April 2022 by Will (talk | contribs) (→‎Example)

Type annotations in python.

Example

from typing import Dict, List, Tuple
from typing import Optional, Union

class Project:
    def ex_param_w_return(user: User) -> Bool

    def ex_type_w_default(active: bool=False) -> None:

    def ex_no_return() -> None:

    def ex_generics(data: List[Dict]):

    def ex_optional() -> Optional[str]:  # nullable type

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

Common Types

dates/times

import datetime

def foo() -> datetime.datetime:
    return datetime.datetime.now()

def foo() -> datetime.date:
    return datetime.date.today()

open file objects

from typing import IO

# either bytes/str
def foo() -> IO:
    return open('foo.txt', 'r')

def foo() -> IO[bytes]:
    return open('foo.txt', 'rb')

def foo() -> IO[str]:
    return open('foo.txt', 'r')

context managers

@contextlib.contextmanager
def foo() -> Iterator[str]:
    print('foo')
    yield 'bar'
    print('baz')