Python typing: Difference between revisions
From wikinotes
Line 39: | Line 39: | ||
== context managers == | == context managers == | ||
<blockquote> | <blockquote> | ||
<syntaxhighlight lang="python"> | |||
@contextlib.contextmanager | |||
def foo() -> Iterator[str]: | |||
print('foo') | |||
yield 'bar' | |||
print('baz') | |||
</syntaxhighlight> | |||
</blockquote><!-- context managers --> | </blockquote><!-- context managers --> | ||
</blockquote><!-- Common Types --> | </blockquote><!-- Common Types --> |
Revision as of 14:16, 31 July 2021
Type annotations in python.
Example
from typing import Dict, List, Tuple, Bool 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
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')