Python typing: Difference between revisions

From wikinotes
No edit summary
Line 36: Line 36:
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- open file objects -->
</blockquote><!-- open file objects -->
== context managers ==
<blockquote>
</blockquote><!-- context managers -->
</blockquote><!-- Common Types -->
</blockquote><!-- Common Types -->

Revision as of 14:06, 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