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 | from typing import Dict, List, Tuple, Optional | ||
class Project: | class Project: | ||
Line 14: | Line 14: | ||
def update_metadata(data: List[Dict]) -> List[Dict]: | def update_metadata(data: List[Dict]) -> List[Dict]: | ||
pass | |||
def grade() -> Optional[str]: # nullable type | |||
pass | pass | ||
</source> | </source> |
Revision as of 16:27, 23 January 2022
Type annotations in python.
Example
from typing import Dict, List, Tuple, Optional class Project: def add_user(user: User) -> Bool pass def set_active(status: bool=False) -> Bool: pass def update_metadata(data: List[Dict]) -> List[Dict]: pass def grade() -> Optional[str]: # nullable type pass
Common Types
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')