Python typing: Difference between revisions

From wikinotes
Line 4: Line 4:
<blockquote>
<blockquote>
<source lang="python">
<source lang="python">
from typing import Dict, List, Tuple, Optional
from typing import Dict, List, Tuple
from typing import Optional, Union


class Project:
class Project:
    # type/return val
     def add_user(user: User) -> Bool
     def add_user(user: User) -> Bool
         pass
         pass


    # type w/ default value
     def set_active(status: bool=False) -> Bool:
     def set_active(status: bool=False) -> Bool:
         pass
         pass


    # generics
     def update_metadata(data: List[Dict]) -> List[Dict]:
     def update_metadata(data: List[Dict]) -> List[Dict]:
         pass
         pass


    # optional
     def grade() -> Optional[str]:  # nullable type
     def grade() -> Optional[str]:  # nullable type
        pass
    # one type or another
    def set_id(id: Union[str, int]) -> None:
         pass
         pass
</source>
</source>

Revision as of 15:05, 3 April 2022

Type annotations in python.

Example

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

class Project:
    # type/return val
    def add_user(user: User) -> Bool
        pass

    # type w/ default value
    def set_active(status: bool=False) -> Bool:
        pass

    # generics
    def update_metadata(data: List[Dict]) -> List[Dict]:
        pass

    # optional
    def grade() -> Optional[str]:  # nullable type
        pass

    # one type or another
    def set_id(id: Union[str, int]) -> None:
        pass

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')