Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Draft] Add types (POC) #243

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 19 additions & 16 deletions notion_client/client.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
"""Synchronous and asynchronous clients for Notion's API."""
import json
import logging
from abc import abstractclassmethod
from abc import abstractmethod
from dataclasses import dataclass
from types import TracebackType
from typing import Any, Dict, List, Optional, Type, Union
from typing import Any, Dict, List, Generic, Optional, Type, Union

import httpx
from httpx import Request, Response
Expand All @@ -24,7 +24,7 @@
is_api_error_code,
)
from notion_client.logging import make_console_logger
from notion_client.typing import SyncAsync
from notion_client.typing import ClientType, ResponseType, SyncAsync


@dataclass
Expand Down Expand Up @@ -52,7 +52,7 @@ class ClientOptions:
notion_version: str = "2022-06-28"


class BaseClient:
class BaseClient(Generic[ClientType]):
def __init__(
self,
client: Union[httpx.Client, httpx.AsyncClient],
Expand All @@ -71,12 +71,12 @@ def __init__(
self._clients: List[Union[httpx.Client, httpx.AsyncClient]] = []
self.client = client

self.blocks = BlocksEndpoint(self)
self.databases = DatabasesEndpoint(self)
self.users = UsersEndpoint(self)
self.pages = PagesEndpoint(self)
self.search = SearchEndpoint(self)
self.comments = CommentsEndpoint(self)
self.blocks = BlocksEndpoint[ClientType](self)
self.databases = DatabasesEndpoint[ClientType](self)
self.users = UsersEndpoint[ClientType](self)
self.pages = PagesEndpoint[ClientType](self)
self.search = SearchEndpoint[ClientType](self)
self.comments = CommentsEndpoint[ClientType](self)

@property
def client(self) -> Union[httpx.Client, httpx.AsyncClient]:
Expand Down Expand Up @@ -131,15 +131,16 @@ def _parse_response(self, response: Response) -> Any:

return body

@abstractclassmethod
@abstractmethod
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good catch

def request(
self,
path: str,
method: str,
cast_to: Type[ResponseType],
Copy link
Owner

@ramnes ramnes Oct 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we avoid to add this new cast_to argument?

query: Optional[Dict[Any, Any]] = None,
body: Optional[Dict[Any, Any]] = None,
auth: Optional[str] = None,
) -> SyncAsync[Any]:
) -> SyncAsync[ResponseType]:
# noqa
pass

Expand Down Expand Up @@ -181,17 +182,18 @@ def request(
self,
path: str,
method: str,
cast_to: Type[ResponseType],
query: Optional[Dict[Any, Any]] = None,
body: Optional[Dict[Any, Any]] = None,
auth: Optional[str] = None,
) -> Any:
) -> ResponseType:
"""Send an HTTP request."""
request = self._build_request(method, path, query, body, auth)
try:
response = self.client.send(request)
except httpx.TimeoutException:
raise RequestTimeoutError()
return self._parse_response(response)
return cast_to(self._parse_response(response))


class AsyncClient(BaseClient):
Expand Down Expand Up @@ -231,14 +233,15 @@ async def request(
self,
path: str,
method: str,
cast_to: Type[ResponseType],
query: Optional[Dict[Any, Any]] = None,
body: Optional[Dict[Any, Any]] = None,
auth: Optional[str] = None,
) -> Any:
) -> ResponseType:
"""Send an HTTP request asynchronously."""
request = self._build_request(method, path, query, body, auth)
try:
response = await self.client.send(request)
except httpx.TimeoutException:
raise RequestTimeoutError()
return self._parse_response(response)
return cast_to(self._parse_response(response))
4 changes: 2 additions & 2 deletions notion_client/helpers.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
"""Utility functions for notion-sdk-py."""
from typing import Any, AsyncGenerator, Awaitable, Callable, Dict, Generator, List
from typing import Any, AsyncGenerator, Awaitable, Callable, Dict, Generator, Mapping, List
from urllib.parse import urlparse
from uuid import UUID


def pick(base: Dict[Any, Any], *keys: str) -> Dict[Any, Any]:
def pick(base: Mapping[Any, Any], *keys: str) -> Dict[Any, Any]:
"""Return a dict composed of key value pairs for keys passed as args."""
result = {}
for key in keys:
Expand Down
8 changes: 7 additions & 1 deletion notion_client/typing.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
"""Custom type definitions for notion-sdk-py."""
from typing import Awaitable, TypeVar, Union
from typing import TYPE_CHECKING, Any, Awaitable, Mapping, TypeVar, Union

if TYPE_CHECKING: # pragma: no cover
from notion_client.client import BaseClient

T = TypeVar("T")
SyncAsync = Union[T, Awaitable[T]]

ClientType = TypeVar("ClientType", bound=BaseClient)
ResponseType = TypeVar("ResponseType", bound=Mapping[Any, Any])
Loading