Python typing: Difference between revisions

From wikinotes
 
No edit summary
Line 1: Line 1:
Adds type annotations to python.
Type annotations in python.
 


= Example =
= Example =
Line 18: Line 17:
</source>
</source>
</blockquote><!-- Example -->
</blockquote><!-- Example -->
= Common Types =
<blockquote>
== open file objects ==
<blockquote>
<syntaxhighlight lang="python">
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')
</syntaxhighlight>
</blockquote><!-- open file objects -->
</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')