Python typing: Difference between revisions
From wikinotes
Line 23: | Line 23: | ||
= Common Types = | = Common Types = | ||
<blockquote> | <blockquote> | ||
== dates/times == | |||
<blockquote> | |||
<syntaxhighlight lang="python"> | |||
import datetime | |||
def foo() -> datetime.datetime: | |||
return datetime.datetime.now() | |||
def foo() -> datetime.date: | |||
return datetime.date.today() | |||
</syntaxhighlight> | |||
</blockquote><!-- dates/times --> | |||
== open file objects == | == open file objects == | ||
<blockquote> | <blockquote> |
Revision as of 14:31, 3 April 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
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')