syncflex 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
syncflex-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Leonardus Chen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,253 @@
1
+ Metadata-Version: 2.3
2
+ Name: syncflex
3
+ Version: 0.1.0
4
+ Summary: Dead-simple interface for sync/async unification
5
+ Author: Leonardus Chen
6
+ Author-email: Leonardus Chen <leonardus.chen@gmail.com>
7
+ License: MIT License
8
+
9
+ Copyright (c) 2025 Leonardus Chen
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+ Requires-Dist: openapi-python-client>=0.26.1
29
+ Requires-Python: >=3.13
30
+ Description-Content-Type: text/markdown
31
+
32
+ # syncflex
33
+
34
+ A tiny Python library that lets you write a single generator function and run it seamlessly in sync or async contexts.
35
+
36
+ It provides two decorators:
37
+
38
+ - `syncify` → turns a generator into a blocking synchronous function.
39
+
40
+ - `asyncify` → turns a generator into an awaitable coroutine function.
41
+
42
+ This allows you to share the same core generator logic in both sync and async code paths without duplication.
43
+
44
+ ---
45
+
46
+ ## 🚀 Installation
47
+
48
+ ```bash
49
+ pip install syncflex
50
+ ```
51
+
52
+ (or copy the ~30 lines of code straight into your project.)
53
+
54
+ ---
55
+
56
+ ## ✨ Motivation
57
+
58
+ Library authors often need to support both synchronous and asynchronous API.
59
+
60
+ Traditionally, that means a lot of duplicated code:
61
+
62
+ ```python
63
+ from typing import Any
64
+
65
+ import httpx
66
+
67
+
68
+ def pre_processing_code() -> Any: ...
69
+
70
+
71
+ def post_processing_code() -> Any: ...
72
+
73
+
74
+ def sync_api_call(http_client: httpx.Client) -> str:
75
+ pre_processing_code()
76
+ pre_processing_code()
77
+ pre_processing_code()
78
+
79
+ response = http_client.request(...)
80
+
81
+ post_processing_code()
82
+ post_processing_code()
83
+ post_processing_code()
84
+
85
+ return "hello"
86
+
87
+
88
+ async def async_api_call(http_client: httpx.AsyncClientClient) -> str:
89
+ pre_processing_code()
90
+ pre_processing_code()
91
+ pre_processing_code()
92
+
93
+ response = await http_client.request(...)
94
+
95
+ post_processing_code()
96
+ post_processing_code()
97
+ post_processing_code()
98
+
99
+ return "hello"
100
+ ```
101
+
102
+ With **syncflex**, you can unify the implementation code and expose both sync and async API like so:
103
+
104
+ ```python
105
+ from collections.abc import Generator
106
+ from typing import Any
107
+
108
+ import httpx
109
+
110
+ from syncflex import asyncify, syncify
111
+
112
+
113
+ def pre_processing_code() -> Any: ...
114
+
115
+
116
+ def post_processing_code() -> Any: ...
117
+
118
+
119
+ def _base_api_call(http_client: httpx.Client | httpx.AsyncClient) -> Generator[Any, Any, str]:
120
+ pre_processing_code()
121
+ pre_processing_code()
122
+ pre_processing_code()
123
+
124
+ response: httpx.Response = yield http_client.request(...)
125
+
126
+ post_processing_code()
127
+ post_processing_code()
128
+ post_processing_code()
129
+
130
+ return "hello"
131
+
132
+
133
+ sync_api_call = syncify(_base_api_call)
134
+ async_api_call = asyncify(_base_api_call)
135
+
136
+ ```
137
+
138
+ ## 📖 Usage
139
+
140
+ ### Simple SDK
141
+
142
+ Below is an quick SDK implementation of [JSONPlaceholder](https://jsonplaceholder.typicode.com).
143
+
144
+ Without **syncflex**:
145
+
146
+ ```python
147
+ from collections.abc import Mapping
148
+ from dataclasses import dataclass
149
+ from typing import Any, Self
150
+
151
+ import httpx
152
+
153
+
154
+ @dataclass
155
+ class Post:
156
+ id: int
157
+ user_id: int
158
+ title: str
159
+ body: str
160
+
161
+ @classmethod
162
+ def from_dict(cls, data: Mapping[str, Any]) -> Self:
163
+ return cls(id=data["id"], user_id=data["userId"], title=data["title"], body=data["body"])
164
+
165
+
166
+ class SyncSDK:
167
+ def __init__(self, http_client: httpx.Client) -> None:
168
+ self._http_client = http_client
169
+
170
+ def get_post(self, id: int) -> Post:
171
+ url = f"/posts/{id}"
172
+ resp: httpx.Response = self._http_client.get(url)
173
+ return Post.from_dict(resp.json())
174
+
175
+ def list_posts(self) -> list[Post]:
176
+ url = "/posts"
177
+ resp: httpx.Response = self._http_client.get(url)
178
+ return [Post.from_dict(data) for data in resp.json()]
179
+
180
+
181
+ class AsyncSDK:
182
+ def __init__(self, http_client: httpx.AsyncClient) -> None:
183
+ self._http_client = http_client
184
+
185
+ async def get_post(self, id: int) -> Post:
186
+ url = f"/posts/{id}"
187
+ resp: httpx.Response = await self._http_client.get(url)
188
+ return Post.from_dict(resp.json())
189
+
190
+ async def list_posts(self) -> list[Post]:
191
+ url = "/posts"
192
+ resp: httpx.Response = await self._http_client.get(url)
193
+ return [Post.from_dict(data) for data in resp.json()]
194
+
195
+ ```
196
+
197
+ With **syncflex**:
198
+
199
+ ```python
200
+ from collections.abc import Generator, Mapping
201
+ from dataclasses import dataclass
202
+ from typing import Any, Self
203
+
204
+ import httpx
205
+
206
+ from syncflex import asyncify, syncify
207
+
208
+
209
+ @dataclass
210
+ class Post:
211
+ id: int
212
+ user_id: int
213
+ title: str
214
+ body: str
215
+
216
+ @classmethod
217
+ def from_dict(cls, data: Mapping[str, Any]) -> Self:
218
+ return cls(id=data["id"], user_id=data["userId"], title=data["title"], body=data["body"])
219
+
220
+
221
+ class BaseSDK:
222
+ def __init__(self, http_client: httpx.Client | httpx.AsyncClient) -> None:
223
+ self._http_client = http_client
224
+
225
+ def _get_post(self, id: int) -> Generator[Any, Any, Post]:
226
+ url = f"/posts/{id}"
227
+ # Yield on the part where it could be sync/async
228
+ resp: httpx.Response = yield self._http_client.get(url)
229
+ return Post.from_dict(resp.json())
230
+
231
+ def _list_posts(self) -> Generator[Any, Any, list[Post]]:
232
+ url = "/posts"
233
+ # Yield on the part where it could be sync/async
234
+ resp: httpx.Response = yield self._http_client.get(url)
235
+ return [Post.from_dict(data) for data in resp.json()]
236
+
237
+
238
+ class SyncSDK(BaseSDK):
239
+ get_post = syncify(BaseSDK._get_post)
240
+ list_posts = syncify(BaseSDK._list_posts)
241
+
242
+
243
+ class AsyncSDK(BaseSDK):
244
+ get_post = asyncify(BaseSDK._get_post)
245
+ list_posts = asyncify(BaseSDK._list_posts)
246
+
247
+ ```
248
+
249
+ See more examples in `examples/`
250
+
251
+ ## ⚖️ License
252
+
253
+ MIT
@@ -0,0 +1,222 @@
1
+ # syncflex
2
+
3
+ A tiny Python library that lets you write a single generator function and run it seamlessly in sync or async contexts.
4
+
5
+ It provides two decorators:
6
+
7
+ - `syncify` → turns a generator into a blocking synchronous function.
8
+
9
+ - `asyncify` → turns a generator into an awaitable coroutine function.
10
+
11
+ This allows you to share the same core generator logic in both sync and async code paths without duplication.
12
+
13
+ ---
14
+
15
+ ## 🚀 Installation
16
+
17
+ ```bash
18
+ pip install syncflex
19
+ ```
20
+
21
+ (or copy the ~30 lines of code straight into your project.)
22
+
23
+ ---
24
+
25
+ ## ✨ Motivation
26
+
27
+ Library authors often need to support both synchronous and asynchronous API.
28
+
29
+ Traditionally, that means a lot of duplicated code:
30
+
31
+ ```python
32
+ from typing import Any
33
+
34
+ import httpx
35
+
36
+
37
+ def pre_processing_code() -> Any: ...
38
+
39
+
40
+ def post_processing_code() -> Any: ...
41
+
42
+
43
+ def sync_api_call(http_client: httpx.Client) -> str:
44
+ pre_processing_code()
45
+ pre_processing_code()
46
+ pre_processing_code()
47
+
48
+ response = http_client.request(...)
49
+
50
+ post_processing_code()
51
+ post_processing_code()
52
+ post_processing_code()
53
+
54
+ return "hello"
55
+
56
+
57
+ async def async_api_call(http_client: httpx.AsyncClientClient) -> str:
58
+ pre_processing_code()
59
+ pre_processing_code()
60
+ pre_processing_code()
61
+
62
+ response = await http_client.request(...)
63
+
64
+ post_processing_code()
65
+ post_processing_code()
66
+ post_processing_code()
67
+
68
+ return "hello"
69
+ ```
70
+
71
+ With **syncflex**, you can unify the implementation code and expose both sync and async API like so:
72
+
73
+ ```python
74
+ from collections.abc import Generator
75
+ from typing import Any
76
+
77
+ import httpx
78
+
79
+ from syncflex import asyncify, syncify
80
+
81
+
82
+ def pre_processing_code() -> Any: ...
83
+
84
+
85
+ def post_processing_code() -> Any: ...
86
+
87
+
88
+ def _base_api_call(http_client: httpx.Client | httpx.AsyncClient) -> Generator[Any, Any, str]:
89
+ pre_processing_code()
90
+ pre_processing_code()
91
+ pre_processing_code()
92
+
93
+ response: httpx.Response = yield http_client.request(...)
94
+
95
+ post_processing_code()
96
+ post_processing_code()
97
+ post_processing_code()
98
+
99
+ return "hello"
100
+
101
+
102
+ sync_api_call = syncify(_base_api_call)
103
+ async_api_call = asyncify(_base_api_call)
104
+
105
+ ```
106
+
107
+ ## 📖 Usage
108
+
109
+ ### Simple SDK
110
+
111
+ Below is an quick SDK implementation of [JSONPlaceholder](https://jsonplaceholder.typicode.com).
112
+
113
+ Without **syncflex**:
114
+
115
+ ```python
116
+ from collections.abc import Mapping
117
+ from dataclasses import dataclass
118
+ from typing import Any, Self
119
+
120
+ import httpx
121
+
122
+
123
+ @dataclass
124
+ class Post:
125
+ id: int
126
+ user_id: int
127
+ title: str
128
+ body: str
129
+
130
+ @classmethod
131
+ def from_dict(cls, data: Mapping[str, Any]) -> Self:
132
+ return cls(id=data["id"], user_id=data["userId"], title=data["title"], body=data["body"])
133
+
134
+
135
+ class SyncSDK:
136
+ def __init__(self, http_client: httpx.Client) -> None:
137
+ self._http_client = http_client
138
+
139
+ def get_post(self, id: int) -> Post:
140
+ url = f"/posts/{id}"
141
+ resp: httpx.Response = self._http_client.get(url)
142
+ return Post.from_dict(resp.json())
143
+
144
+ def list_posts(self) -> list[Post]:
145
+ url = "/posts"
146
+ resp: httpx.Response = self._http_client.get(url)
147
+ return [Post.from_dict(data) for data in resp.json()]
148
+
149
+
150
+ class AsyncSDK:
151
+ def __init__(self, http_client: httpx.AsyncClient) -> None:
152
+ self._http_client = http_client
153
+
154
+ async def get_post(self, id: int) -> Post:
155
+ url = f"/posts/{id}"
156
+ resp: httpx.Response = await self._http_client.get(url)
157
+ return Post.from_dict(resp.json())
158
+
159
+ async def list_posts(self) -> list[Post]:
160
+ url = "/posts"
161
+ resp: httpx.Response = await self._http_client.get(url)
162
+ return [Post.from_dict(data) for data in resp.json()]
163
+
164
+ ```
165
+
166
+ With **syncflex**:
167
+
168
+ ```python
169
+ from collections.abc import Generator, Mapping
170
+ from dataclasses import dataclass
171
+ from typing import Any, Self
172
+
173
+ import httpx
174
+
175
+ from syncflex import asyncify, syncify
176
+
177
+
178
+ @dataclass
179
+ class Post:
180
+ id: int
181
+ user_id: int
182
+ title: str
183
+ body: str
184
+
185
+ @classmethod
186
+ def from_dict(cls, data: Mapping[str, Any]) -> Self:
187
+ return cls(id=data["id"], user_id=data["userId"], title=data["title"], body=data["body"])
188
+
189
+
190
+ class BaseSDK:
191
+ def __init__(self, http_client: httpx.Client | httpx.AsyncClient) -> None:
192
+ self._http_client = http_client
193
+
194
+ def _get_post(self, id: int) -> Generator[Any, Any, Post]:
195
+ url = f"/posts/{id}"
196
+ # Yield on the part where it could be sync/async
197
+ resp: httpx.Response = yield self._http_client.get(url)
198
+ return Post.from_dict(resp.json())
199
+
200
+ def _list_posts(self) -> Generator[Any, Any, list[Post]]:
201
+ url = "/posts"
202
+ # Yield on the part where it could be sync/async
203
+ resp: httpx.Response = yield self._http_client.get(url)
204
+ return [Post.from_dict(data) for data in resp.json()]
205
+
206
+
207
+ class SyncSDK(BaseSDK):
208
+ get_post = syncify(BaseSDK._get_post)
209
+ list_posts = syncify(BaseSDK._list_posts)
210
+
211
+
212
+ class AsyncSDK(BaseSDK):
213
+ get_post = asyncify(BaseSDK._get_post)
214
+ list_posts = asyncify(BaseSDK._list_posts)
215
+
216
+ ```
217
+
218
+ See more examples in `examples/`
219
+
220
+ ## ⚖️ License
221
+
222
+ MIT
@@ -0,0 +1,42 @@
1
+ [project]
2
+ name = "syncflex"
3
+ version = "0.1.0"
4
+ description = "Dead-simple interface for sync/async unification"
5
+ readme = "README.md"
6
+ requires-python = ">=3.13"
7
+ license = { file = "LICENSE" }
8
+ authors = [{ name = "Leonardus Chen", email = "leonardus.chen@gmail.com" }]
9
+ dependencies = [
10
+ "openapi-python-client>=0.26.1",
11
+ ]
12
+
13
+ [build-system]
14
+ requires = ["uv_build>=0.8.19,<0.9.0"]
15
+ build-backend = "uv_build"
16
+
17
+ [tool.uv.build-backend]
18
+ module-root = "." # Indicates a flat layout
19
+
20
+ [tool.ruff]
21
+ line-length = 120
22
+ target-version = "py313"
23
+
24
+ [tool.ruff.lint]
25
+ select = ["E", "F", "UP", "B", "SIM", "I"]
26
+
27
+ [tool.mypy]
28
+ python_version = "3.13"
29
+ strict = true
30
+ exclude = [".venv"]
31
+
32
+ [dependency-groups]
33
+ dev = [
34
+ "pytest==8.*",
35
+ "ruff==0.*",
36
+ "mypy==1.*",
37
+ "coverage==7.*",
38
+ "pytest-asyncio==1.*",
39
+ ]
40
+ example = [
41
+ "httpx==0.*",
42
+ ]
@@ -0,0 +1,2 @@
1
+ from syncflex._core import asyncify as asyncify
2
+ from syncflex._core import syncify as syncify
@@ -0,0 +1,33 @@
1
+ from collections.abc import Callable, Coroutine, Generator
2
+ from typing import Any
3
+
4
+
5
+ def syncify[**P, RT](f: Callable[P, Generator[Any, Any, RT]]) -> Callable[P, RT]:
6
+ def func(*args: P.args, **kwargs: P.kwargs) -> RT:
7
+ gen = f(*args, **kwargs)
8
+ task: Any = None
9
+ while True:
10
+ try:
11
+ res = task
12
+ task = gen.send(res)
13
+ except StopIteration as e:
14
+ return e.value # type: ignore[no-any-return]
15
+
16
+ return func
17
+
18
+
19
+ def asyncify[**P, RT](f: Callable[P, Generator[Any, Any, RT]]) -> Callable[P, Coroutine[Any, Any, RT]]:
20
+ async def initial_coro() -> None:
21
+ return None
22
+
23
+ async def func(*args: P.args, **kwargs: P.kwargs) -> RT:
24
+ gen = f(*args, **kwargs)
25
+ task: Coroutine[Any, Any, Any] = initial_coro()
26
+ while True:
27
+ try:
28
+ res = await task
29
+ task = gen.send(res)
30
+ except StopIteration as e:
31
+ return e.value # type: ignore[no-any-return]
32
+
33
+ return func
File without changes