growsurf-python 0.0.2__py3-none-any.whl

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.
Files changed (80) hide show
  1. growsurf/__init__.py +102 -0
  2. growsurf/_base_client.py +2153 -0
  3. growsurf/_client.py +484 -0
  4. growsurf/_compat.py +226 -0
  5. growsurf/_constants.py +14 -0
  6. growsurf/_exceptions.py +108 -0
  7. growsurf/_files.py +173 -0
  8. growsurf/_models.py +878 -0
  9. growsurf/_qs.py +149 -0
  10. growsurf/_resource.py +43 -0
  11. growsurf/_response.py +833 -0
  12. growsurf/_streaming.py +338 -0
  13. growsurf/_types.py +274 -0
  14. growsurf/_utils/__init__.py +64 -0
  15. growsurf/_utils/_compat.py +45 -0
  16. growsurf/_utils/_datetime_parse.py +136 -0
  17. growsurf/_utils/_json.py +35 -0
  18. growsurf/_utils/_logs.py +25 -0
  19. growsurf/_utils/_path.py +127 -0
  20. growsurf/_utils/_proxy.py +65 -0
  21. growsurf/_utils/_reflection.py +42 -0
  22. growsurf/_utils/_resources_proxy.py +24 -0
  23. growsurf/_utils/_streams.py +12 -0
  24. growsurf/_utils/_sync.py +58 -0
  25. growsurf/_utils/_transform.py +457 -0
  26. growsurf/_utils/_typing.py +156 -0
  27. growsurf/_utils/_utils.py +433 -0
  28. growsurf/_version.py +4 -0
  29. growsurf/lib/.keep +4 -0
  30. growsurf/py.typed +0 -0
  31. growsurf/resources/__init__.py +19 -0
  32. growsurf/resources/campaign/__init__.py +61 -0
  33. growsurf/resources/campaign/campaign.py +1126 -0
  34. growsurf/resources/campaign/commission.py +259 -0
  35. growsurf/resources/campaign/participant.py +1587 -0
  36. growsurf/resources/campaign/reward.py +355 -0
  37. growsurf/types/__init__.py +18 -0
  38. growsurf/types/campaign/__init__.py +35 -0
  39. growsurf/types/campaign/campaign.py +73 -0
  40. growsurf/types/campaign/commission_approve_response.py +9 -0
  41. growsurf/types/campaign/commission_delete_response.py +9 -0
  42. growsurf/types/campaign/fraud_risk_level.py +7 -0
  43. growsurf/types/campaign/participant.py +147 -0
  44. growsurf/types/campaign/participant_add_params.py +30 -0
  45. growsurf/types/campaign/participant_delete_response.py +9 -0
  46. growsurf/types/campaign/participant_list_commissions_params.py +22 -0
  47. growsurf/types/campaign/participant_list_payouts_params.py +22 -0
  48. growsurf/types/campaign/participant_list_referrals_params.py +43 -0
  49. growsurf/types/campaign/participant_list_rewards_params.py +19 -0
  50. growsurf/types/campaign/participant_list_rewards_response.py +18 -0
  51. growsurf/types/campaign/participant_record_transaction_params.py +60 -0
  52. growsurf/types/campaign/participant_record_transaction_response.py +37 -0
  53. growsurf/types/campaign/participant_reward.py +39 -0
  54. growsurf/types/campaign/participant_send_invites_params.py +20 -0
  55. growsurf/types/campaign/participant_send_invites_response.py +15 -0
  56. growsurf/types/campaign/participant_trigger_referral_response.py +13 -0
  57. growsurf/types/campaign/participant_update_params.py +34 -0
  58. growsurf/types/campaign/referral_source.py +7 -0
  59. growsurf/types/campaign/referral_status.py +7 -0
  60. growsurf/types/campaign/reward_approve_params.py +14 -0
  61. growsurf/types/campaign/reward_approve_response.py +9 -0
  62. growsurf/types/campaign/reward_delete_response.py +9 -0
  63. growsurf/types/campaign/reward_fulfill_response.py +9 -0
  64. growsurf/types/campaign_list_commissions_params.py +20 -0
  65. growsurf/types/campaign_list_leaderboard_params.py +36 -0
  66. growsurf/types/campaign_list_participants_params.py +17 -0
  67. growsurf/types/campaign_list_payouts_params.py +20 -0
  68. growsurf/types/campaign_list_referrals_params.py +41 -0
  69. growsurf/types/campaign_list_response.py +12 -0
  70. growsurf/types/campaign_retrieve_analytics_params.py +26 -0
  71. growsurf/types/campaign_retrieve_analytics_response.py +75 -0
  72. growsurf/types/commission_structure.py +62 -0
  73. growsurf/types/participant_commission_list.py +62 -0
  74. growsurf/types/participant_list.py +18 -0
  75. growsurf/types/participant_payout_list.py +50 -0
  76. growsurf/types/referral_list.py +40 -0
  77. growsurf_python-0.0.2.dist-info/METADATA +399 -0
  78. growsurf_python-0.0.2.dist-info/RECORD +80 -0
  79. growsurf_python-0.0.2.dist-info/WHEEL +4 -0
  80. growsurf_python-0.0.2.dist-info/licenses/LICENSE +201 -0
growsurf/_client.py ADDED
@@ -0,0 +1,484 @@
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import TYPE_CHECKING, Any, Mapping
7
+ from typing_extensions import Self, override
8
+
9
+ import httpx
10
+
11
+ from . import _exceptions
12
+ from ._qs import Querystring
13
+ from ._types import (
14
+ Omit,
15
+ Timeout,
16
+ NotGiven,
17
+ Transport,
18
+ ProxiesTypes,
19
+ RequestOptions,
20
+ not_given,
21
+ )
22
+ from ._utils import (
23
+ is_given,
24
+ is_mapping_t,
25
+ get_async_library,
26
+ )
27
+ from ._compat import cached_property
28
+ from ._models import SecurityOptions
29
+ from ._version import __version__
30
+ from ._streaming import Stream as Stream, AsyncStream as AsyncStream
31
+ from ._exceptions import GrowsurfError, APIStatusError
32
+ from ._base_client import (
33
+ DEFAULT_MAX_RETRIES,
34
+ SyncAPIClient,
35
+ AsyncAPIClient,
36
+ )
37
+
38
+ if TYPE_CHECKING:
39
+ from .resources import campaign
40
+ from .resources.campaign.campaign import CampaignResource, AsyncCampaignResource
41
+
42
+ __all__ = [
43
+ "Timeout",
44
+ "Transport",
45
+ "ProxiesTypes",
46
+ "RequestOptions",
47
+ "Growsurf",
48
+ "AsyncGrowsurf",
49
+ "Client",
50
+ "AsyncClient",
51
+ ]
52
+
53
+
54
+ class Growsurf(SyncAPIClient):
55
+ # client options
56
+ api_key: str
57
+
58
+ def __init__(
59
+ self,
60
+ *,
61
+ api_key: str | None = None,
62
+ base_url: str | httpx.URL | None = None,
63
+ timeout: float | Timeout | None | NotGiven = not_given,
64
+ max_retries: int = DEFAULT_MAX_RETRIES,
65
+ default_headers: Mapping[str, str] | None = None,
66
+ default_query: Mapping[str, object] | None = None,
67
+ # Configure a custom httpx client.
68
+ # We provide a `DefaultHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`.
69
+ # See the [httpx documentation](https://www.python-httpx.org/api/#client) for more details.
70
+ http_client: httpx.Client | None = None,
71
+ # Enable or disable schema validation for data returned by the API.
72
+ # When enabled an error APIResponseValidationError is raised
73
+ # if the API responds with invalid data for the expected schema.
74
+ #
75
+ # This parameter may be removed or changed in the future.
76
+ # If you rely on this feature, please open a GitHub issue
77
+ # outlining your use-case to help us decide if it should be
78
+ # part of our public interface in the future.
79
+ _strict_response_validation: bool = False,
80
+ ) -> None:
81
+ """Construct a new synchronous Growsurf client instance.
82
+
83
+ This automatically infers the `api_key` argument from the `GROWSURF_API_KEY` environment variable if it is not provided.
84
+ """
85
+ if api_key is None:
86
+ api_key = os.environ.get("GROWSURF_API_KEY")
87
+ if api_key is None:
88
+ raise GrowsurfError(
89
+ "The api_key client option must be set either by passing api_key to the client or by setting the GROWSURF_API_KEY environment variable"
90
+ )
91
+ self.api_key = api_key
92
+
93
+ if base_url is None:
94
+ base_url = os.environ.get("GROWSURF_BASE_URL")
95
+ if base_url is None:
96
+ base_url = f"https://api.growsurf.com/v2"
97
+
98
+ custom_headers_env = os.environ.get("GROWSURF_CUSTOM_HEADERS")
99
+ if custom_headers_env is not None:
100
+ parsed: dict[str, str] = {}
101
+ for line in custom_headers_env.split("\n"):
102
+ colon = line.find(":")
103
+ if colon >= 0:
104
+ parsed[line[:colon].strip()] = line[colon + 1 :].strip()
105
+ default_headers = {**parsed, **(default_headers if is_mapping_t(default_headers) else {})}
106
+
107
+ super().__init__(
108
+ version=__version__,
109
+ base_url=base_url,
110
+ max_retries=max_retries,
111
+ timeout=timeout,
112
+ http_client=http_client,
113
+ custom_headers=default_headers,
114
+ custom_query=default_query,
115
+ _strict_response_validation=_strict_response_validation,
116
+ )
117
+
118
+ @cached_property
119
+ def campaign(self) -> CampaignResource:
120
+ from .resources.campaign import CampaignResource
121
+
122
+ return CampaignResource(self)
123
+
124
+ @cached_property
125
+ def with_raw_response(self) -> GrowsurfWithRawResponse:
126
+ return GrowsurfWithRawResponse(self)
127
+
128
+ @cached_property
129
+ def with_streaming_response(self) -> GrowsurfWithStreamedResponse:
130
+ return GrowsurfWithStreamedResponse(self)
131
+
132
+ @property
133
+ @override
134
+ def qs(self) -> Querystring:
135
+ return Querystring(array_format="comma")
136
+
137
+ @override
138
+ def _auth_headers(self, security: SecurityOptions) -> dict[str, str]:
139
+ return {
140
+ **(self._api_key_auth if security.get("api_key_auth", False) else {}),
141
+ }
142
+
143
+ @property
144
+ def _api_key_auth(self) -> dict[str, str]:
145
+ api_key = self.api_key
146
+ return {"Authorization": f"Bearer {api_key}"}
147
+
148
+ @property
149
+ @override
150
+ def default_headers(self) -> dict[str, str | Omit]:
151
+ return {
152
+ **super().default_headers,
153
+ "X-Stainless-Async": "false",
154
+ **self._custom_headers,
155
+ }
156
+
157
+ def copy(
158
+ self,
159
+ *,
160
+ api_key: str | None = None,
161
+ base_url: str | httpx.URL | None = None,
162
+ timeout: float | Timeout | None | NotGiven = not_given,
163
+ http_client: httpx.Client | None = None,
164
+ max_retries: int | NotGiven = not_given,
165
+ default_headers: Mapping[str, str] | None = None,
166
+ set_default_headers: Mapping[str, str] | None = None,
167
+ default_query: Mapping[str, object] | None = None,
168
+ set_default_query: Mapping[str, object] | None = None,
169
+ _extra_kwargs: Mapping[str, Any] = {},
170
+ ) -> Self:
171
+ """
172
+ Create a new client instance re-using the same options given to the current client with optional overriding.
173
+ """
174
+ if default_headers is not None and set_default_headers is not None:
175
+ raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive")
176
+
177
+ if default_query is not None and set_default_query is not None:
178
+ raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive")
179
+
180
+ headers = self._custom_headers
181
+ if default_headers is not None:
182
+ headers = {**headers, **default_headers}
183
+ elif set_default_headers is not None:
184
+ headers = set_default_headers
185
+
186
+ params = self._custom_query
187
+ if default_query is not None:
188
+ params = {**params, **default_query}
189
+ elif set_default_query is not None:
190
+ params = set_default_query
191
+
192
+ http_client = http_client or self._client
193
+ return self.__class__(
194
+ api_key=api_key or self.api_key,
195
+ base_url=base_url or self.base_url,
196
+ timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
197
+ http_client=http_client,
198
+ max_retries=max_retries if is_given(max_retries) else self.max_retries,
199
+ default_headers=headers,
200
+ default_query=params,
201
+ **_extra_kwargs,
202
+ )
203
+
204
+ # Alias for `copy` for nicer inline usage, e.g.
205
+ # client.with_options(timeout=10).foo.create(...)
206
+ with_options = copy
207
+
208
+ @override
209
+ def _make_status_error(
210
+ self,
211
+ err_msg: str,
212
+ *,
213
+ body: object,
214
+ response: httpx.Response,
215
+ ) -> APIStatusError:
216
+ if response.status_code == 400:
217
+ return _exceptions.BadRequestError(err_msg, response=response, body=body)
218
+
219
+ if response.status_code == 401:
220
+ return _exceptions.AuthenticationError(err_msg, response=response, body=body)
221
+
222
+ if response.status_code == 403:
223
+ return _exceptions.PermissionDeniedError(err_msg, response=response, body=body)
224
+
225
+ if response.status_code == 404:
226
+ return _exceptions.NotFoundError(err_msg, response=response, body=body)
227
+
228
+ if response.status_code == 409:
229
+ return _exceptions.ConflictError(err_msg, response=response, body=body)
230
+
231
+ if response.status_code == 422:
232
+ return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body)
233
+
234
+ if response.status_code == 429:
235
+ return _exceptions.RateLimitError(err_msg, response=response, body=body)
236
+
237
+ if response.status_code >= 500:
238
+ return _exceptions.InternalServerError(err_msg, response=response, body=body)
239
+ return APIStatusError(err_msg, response=response, body=body)
240
+
241
+
242
+ class AsyncGrowsurf(AsyncAPIClient):
243
+ # client options
244
+ api_key: str
245
+
246
+ def __init__(
247
+ self,
248
+ *,
249
+ api_key: str | None = None,
250
+ base_url: str | httpx.URL | None = None,
251
+ timeout: float | Timeout | None | NotGiven = not_given,
252
+ max_retries: int = DEFAULT_MAX_RETRIES,
253
+ default_headers: Mapping[str, str] | None = None,
254
+ default_query: Mapping[str, object] | None = None,
255
+ # Configure a custom httpx client.
256
+ # We provide a `DefaultAsyncHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`.
257
+ # See the [httpx documentation](https://www.python-httpx.org/api/#asyncclient) for more details.
258
+ http_client: httpx.AsyncClient | None = None,
259
+ # Enable or disable schema validation for data returned by the API.
260
+ # When enabled an error APIResponseValidationError is raised
261
+ # if the API responds with invalid data for the expected schema.
262
+ #
263
+ # This parameter may be removed or changed in the future.
264
+ # If you rely on this feature, please open a GitHub issue
265
+ # outlining your use-case to help us decide if it should be
266
+ # part of our public interface in the future.
267
+ _strict_response_validation: bool = False,
268
+ ) -> None:
269
+ """Construct a new async AsyncGrowsurf client instance.
270
+
271
+ This automatically infers the `api_key` argument from the `GROWSURF_API_KEY` environment variable if it is not provided.
272
+ """
273
+ if api_key is None:
274
+ api_key = os.environ.get("GROWSURF_API_KEY")
275
+ if api_key is None:
276
+ raise GrowsurfError(
277
+ "The api_key client option must be set either by passing api_key to the client or by setting the GROWSURF_API_KEY environment variable"
278
+ )
279
+ self.api_key = api_key
280
+
281
+ if base_url is None:
282
+ base_url = os.environ.get("GROWSURF_BASE_URL")
283
+ if base_url is None:
284
+ base_url = f"https://api.growsurf.com/v2"
285
+
286
+ custom_headers_env = os.environ.get("GROWSURF_CUSTOM_HEADERS")
287
+ if custom_headers_env is not None:
288
+ parsed: dict[str, str] = {}
289
+ for line in custom_headers_env.split("\n"):
290
+ colon = line.find(":")
291
+ if colon >= 0:
292
+ parsed[line[:colon].strip()] = line[colon + 1 :].strip()
293
+ default_headers = {**parsed, **(default_headers if is_mapping_t(default_headers) else {})}
294
+
295
+ super().__init__(
296
+ version=__version__,
297
+ base_url=base_url,
298
+ max_retries=max_retries,
299
+ timeout=timeout,
300
+ http_client=http_client,
301
+ custom_headers=default_headers,
302
+ custom_query=default_query,
303
+ _strict_response_validation=_strict_response_validation,
304
+ )
305
+
306
+ @cached_property
307
+ def campaign(self) -> AsyncCampaignResource:
308
+ from .resources.campaign import AsyncCampaignResource
309
+
310
+ return AsyncCampaignResource(self)
311
+
312
+ @cached_property
313
+ def with_raw_response(self) -> AsyncGrowsurfWithRawResponse:
314
+ return AsyncGrowsurfWithRawResponse(self)
315
+
316
+ @cached_property
317
+ def with_streaming_response(self) -> AsyncGrowsurfWithStreamedResponse:
318
+ return AsyncGrowsurfWithStreamedResponse(self)
319
+
320
+ @property
321
+ @override
322
+ def qs(self) -> Querystring:
323
+ return Querystring(array_format="comma")
324
+
325
+ @override
326
+ def _auth_headers(self, security: SecurityOptions) -> dict[str, str]:
327
+ return {
328
+ **(self._api_key_auth if security.get("api_key_auth", False) else {}),
329
+ }
330
+
331
+ @property
332
+ def _api_key_auth(self) -> dict[str, str]:
333
+ api_key = self.api_key
334
+ return {"Authorization": f"Bearer {api_key}"}
335
+
336
+ @property
337
+ @override
338
+ def default_headers(self) -> dict[str, str | Omit]:
339
+ return {
340
+ **super().default_headers,
341
+ "X-Stainless-Async": f"async:{get_async_library()}",
342
+ **self._custom_headers,
343
+ }
344
+
345
+ def copy(
346
+ self,
347
+ *,
348
+ api_key: str | None = None,
349
+ base_url: str | httpx.URL | None = None,
350
+ timeout: float | Timeout | None | NotGiven = not_given,
351
+ http_client: httpx.AsyncClient | None = None,
352
+ max_retries: int | NotGiven = not_given,
353
+ default_headers: Mapping[str, str] | None = None,
354
+ set_default_headers: Mapping[str, str] | None = None,
355
+ default_query: Mapping[str, object] | None = None,
356
+ set_default_query: Mapping[str, object] | None = None,
357
+ _extra_kwargs: Mapping[str, Any] = {},
358
+ ) -> Self:
359
+ """
360
+ Create a new client instance re-using the same options given to the current client with optional overriding.
361
+ """
362
+ if default_headers is not None and set_default_headers is not None:
363
+ raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive")
364
+
365
+ if default_query is not None and set_default_query is not None:
366
+ raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive")
367
+
368
+ headers = self._custom_headers
369
+ if default_headers is not None:
370
+ headers = {**headers, **default_headers}
371
+ elif set_default_headers is not None:
372
+ headers = set_default_headers
373
+
374
+ params = self._custom_query
375
+ if default_query is not None:
376
+ params = {**params, **default_query}
377
+ elif set_default_query is not None:
378
+ params = set_default_query
379
+
380
+ http_client = http_client or self._client
381
+ return self.__class__(
382
+ api_key=api_key or self.api_key,
383
+ base_url=base_url or self.base_url,
384
+ timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
385
+ http_client=http_client,
386
+ max_retries=max_retries if is_given(max_retries) else self.max_retries,
387
+ default_headers=headers,
388
+ default_query=params,
389
+ **_extra_kwargs,
390
+ )
391
+
392
+ # Alias for `copy` for nicer inline usage, e.g.
393
+ # client.with_options(timeout=10).foo.create(...)
394
+ with_options = copy
395
+
396
+ @override
397
+ def _make_status_error(
398
+ self,
399
+ err_msg: str,
400
+ *,
401
+ body: object,
402
+ response: httpx.Response,
403
+ ) -> APIStatusError:
404
+ if response.status_code == 400:
405
+ return _exceptions.BadRequestError(err_msg, response=response, body=body)
406
+
407
+ if response.status_code == 401:
408
+ return _exceptions.AuthenticationError(err_msg, response=response, body=body)
409
+
410
+ if response.status_code == 403:
411
+ return _exceptions.PermissionDeniedError(err_msg, response=response, body=body)
412
+
413
+ if response.status_code == 404:
414
+ return _exceptions.NotFoundError(err_msg, response=response, body=body)
415
+
416
+ if response.status_code == 409:
417
+ return _exceptions.ConflictError(err_msg, response=response, body=body)
418
+
419
+ if response.status_code == 422:
420
+ return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body)
421
+
422
+ if response.status_code == 429:
423
+ return _exceptions.RateLimitError(err_msg, response=response, body=body)
424
+
425
+ if response.status_code >= 500:
426
+ return _exceptions.InternalServerError(err_msg, response=response, body=body)
427
+ return APIStatusError(err_msg, response=response, body=body)
428
+
429
+
430
+ class GrowsurfWithRawResponse:
431
+ _client: Growsurf
432
+
433
+ def __init__(self, client: Growsurf) -> None:
434
+ self._client = client
435
+
436
+ @cached_property
437
+ def campaign(self) -> campaign.CampaignResourceWithRawResponse:
438
+ from .resources.campaign import CampaignResourceWithRawResponse
439
+
440
+ return CampaignResourceWithRawResponse(self._client.campaign)
441
+
442
+
443
+ class AsyncGrowsurfWithRawResponse:
444
+ _client: AsyncGrowsurf
445
+
446
+ def __init__(self, client: AsyncGrowsurf) -> None:
447
+ self._client = client
448
+
449
+ @cached_property
450
+ def campaign(self) -> campaign.AsyncCampaignResourceWithRawResponse:
451
+ from .resources.campaign import AsyncCampaignResourceWithRawResponse
452
+
453
+ return AsyncCampaignResourceWithRawResponse(self._client.campaign)
454
+
455
+
456
+ class GrowsurfWithStreamedResponse:
457
+ _client: Growsurf
458
+
459
+ def __init__(self, client: Growsurf) -> None:
460
+ self._client = client
461
+
462
+ @cached_property
463
+ def campaign(self) -> campaign.CampaignResourceWithStreamingResponse:
464
+ from .resources.campaign import CampaignResourceWithStreamingResponse
465
+
466
+ return CampaignResourceWithStreamingResponse(self._client.campaign)
467
+
468
+
469
+ class AsyncGrowsurfWithStreamedResponse:
470
+ _client: AsyncGrowsurf
471
+
472
+ def __init__(self, client: AsyncGrowsurf) -> None:
473
+ self._client = client
474
+
475
+ @cached_property
476
+ def campaign(self) -> campaign.AsyncCampaignResourceWithStreamingResponse:
477
+ from .resources.campaign import AsyncCampaignResourceWithStreamingResponse
478
+
479
+ return AsyncCampaignResourceWithStreamingResponse(self._client.campaign)
480
+
481
+
482
+ Client = Growsurf
483
+
484
+ AsyncClient = AsyncGrowsurf
growsurf/_compat.py ADDED
@@ -0,0 +1,226 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast, overload
4
+ from datetime import date, datetime
5
+ from typing_extensions import Self, Literal, TypedDict
6
+
7
+ import pydantic
8
+ from pydantic.fields import FieldInfo
9
+
10
+ from ._types import IncEx, StrBytesIntFloat
11
+
12
+ _T = TypeVar("_T")
13
+ _ModelT = TypeVar("_ModelT", bound=pydantic.BaseModel)
14
+
15
+ # --------------- Pydantic v2, v3 compatibility ---------------
16
+
17
+ # Pyright incorrectly reports some of our functions as overriding a method when they don't
18
+ # pyright: reportIncompatibleMethodOverride=false
19
+
20
+ PYDANTIC_V1 = pydantic.VERSION.startswith("1.")
21
+
22
+ if TYPE_CHECKING:
23
+
24
+ def parse_date(value: date | StrBytesIntFloat) -> date: # noqa: ARG001
25
+ ...
26
+
27
+ def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: # noqa: ARG001
28
+ ...
29
+
30
+ def get_args(t: type[Any]) -> tuple[Any, ...]: # noqa: ARG001
31
+ ...
32
+
33
+ def is_union(tp: type[Any] | None) -> bool: # noqa: ARG001
34
+ ...
35
+
36
+ def get_origin(t: type[Any]) -> type[Any] | None: # noqa: ARG001
37
+ ...
38
+
39
+ def is_literal_type(type_: type[Any]) -> bool: # noqa: ARG001
40
+ ...
41
+
42
+ def is_typeddict(type_: type[Any]) -> bool: # noqa: ARG001
43
+ ...
44
+
45
+ else:
46
+ # v1 re-exports
47
+ if PYDANTIC_V1:
48
+ from pydantic.typing import (
49
+ get_args as get_args,
50
+ is_union as is_union,
51
+ get_origin as get_origin,
52
+ is_typeddict as is_typeddict,
53
+ is_literal_type as is_literal_type,
54
+ )
55
+ from pydantic.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime
56
+ else:
57
+ from ._utils import (
58
+ get_args as get_args,
59
+ is_union as is_union,
60
+ get_origin as get_origin,
61
+ parse_date as parse_date,
62
+ is_typeddict as is_typeddict,
63
+ parse_datetime as parse_datetime,
64
+ is_literal_type as is_literal_type,
65
+ )
66
+
67
+
68
+ # refactored config
69
+ if TYPE_CHECKING:
70
+ from pydantic import ConfigDict as ConfigDict
71
+ else:
72
+ if PYDANTIC_V1:
73
+ # TODO: provide an error message here?
74
+ ConfigDict = None
75
+ else:
76
+ from pydantic import ConfigDict as ConfigDict
77
+
78
+
79
+ # renamed methods / properties
80
+ def parse_obj(model: type[_ModelT], value: object) -> _ModelT:
81
+ if PYDANTIC_V1:
82
+ return cast(_ModelT, model.parse_obj(value)) # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
83
+ else:
84
+ return model.model_validate(value)
85
+
86
+
87
+ def field_is_required(field: FieldInfo) -> bool:
88
+ if PYDANTIC_V1:
89
+ return field.required # type: ignore
90
+ return field.is_required()
91
+
92
+
93
+ def field_get_default(field: FieldInfo) -> Any:
94
+ value = field.get_default()
95
+ if PYDANTIC_V1:
96
+ return value
97
+ from pydantic_core import PydanticUndefined
98
+
99
+ if value == PydanticUndefined:
100
+ return None
101
+ return value
102
+
103
+
104
+ def field_outer_type(field: FieldInfo) -> Any:
105
+ if PYDANTIC_V1:
106
+ return field.outer_type_ # type: ignore
107
+ return field.annotation
108
+
109
+
110
+ def get_model_config(model: type[pydantic.BaseModel]) -> Any:
111
+ if PYDANTIC_V1:
112
+ return model.__config__ # type: ignore
113
+ return model.model_config
114
+
115
+
116
+ def get_model_fields(model: type[pydantic.BaseModel]) -> dict[str, FieldInfo]:
117
+ if PYDANTIC_V1:
118
+ return model.__fields__ # type: ignore
119
+ return model.model_fields
120
+
121
+
122
+ def model_copy(model: _ModelT, *, deep: bool = False) -> _ModelT:
123
+ if PYDANTIC_V1:
124
+ return model.copy(deep=deep) # type: ignore
125
+ return model.model_copy(deep=deep)
126
+
127
+
128
+ def model_json(model: pydantic.BaseModel, *, indent: int | None = None) -> str:
129
+ if PYDANTIC_V1:
130
+ return model.json(indent=indent) # type: ignore
131
+ return model.model_dump_json(indent=indent)
132
+
133
+
134
+ class _ModelDumpKwargs(TypedDict, total=False):
135
+ by_alias: bool
136
+
137
+
138
+ def model_dump(
139
+ model: pydantic.BaseModel,
140
+ *,
141
+ exclude: IncEx | None = None,
142
+ exclude_unset: bool = False,
143
+ exclude_defaults: bool = False,
144
+ warnings: bool = True,
145
+ mode: Literal["json", "python"] = "python",
146
+ by_alias: bool | None = None,
147
+ ) -> dict[str, Any]:
148
+ if (not PYDANTIC_V1) or hasattr(model, "model_dump"):
149
+ kwargs: _ModelDumpKwargs = {}
150
+ if by_alias is not None:
151
+ kwargs["by_alias"] = by_alias
152
+ return model.model_dump(
153
+ mode=mode,
154
+ exclude=exclude,
155
+ exclude_unset=exclude_unset,
156
+ exclude_defaults=exclude_defaults,
157
+ # warnings are not supported in Pydantic v1
158
+ warnings=True if PYDANTIC_V1 else warnings,
159
+ **kwargs,
160
+ )
161
+ return cast(
162
+ "dict[str, Any]",
163
+ model.dict( # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
164
+ exclude=exclude, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, by_alias=bool(by_alias)
165
+ ),
166
+ )
167
+
168
+
169
+ def model_parse(model: type[_ModelT], data: Any) -> _ModelT:
170
+ if PYDANTIC_V1:
171
+ return model.parse_obj(data) # pyright: ignore[reportDeprecated]
172
+ return model.model_validate(data)
173
+
174
+
175
+ # generic models
176
+ if TYPE_CHECKING:
177
+
178
+ class GenericModel(pydantic.BaseModel): ...
179
+
180
+ else:
181
+ if PYDANTIC_V1:
182
+ import pydantic.generics
183
+
184
+ class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel): ...
185
+ else:
186
+ # there no longer needs to be a distinction in v2 but
187
+ # we still have to create our own subclass to avoid
188
+ # inconsistent MRO ordering errors
189
+ class GenericModel(pydantic.BaseModel): ...
190
+
191
+
192
+ # cached properties
193
+ if TYPE_CHECKING:
194
+ cached_property = property
195
+
196
+ # we define a separate type (copied from typeshed)
197
+ # that represents that `cached_property` is `set`able
198
+ # at runtime, which differs from `@property`.
199
+ #
200
+ # this is a separate type as editors likely special case
201
+ # `@property` and we don't want to cause issues just to have
202
+ # more helpful internal types.
203
+
204
+ class typed_cached_property(Generic[_T]):
205
+ func: Callable[[Any], _T]
206
+ attrname: str | None
207
+
208
+ def __init__(self, func: Callable[[Any], _T]) -> None: ...
209
+
210
+ @overload
211
+ def __get__(self, instance: None, owner: type[Any] | None = None) -> Self: ...
212
+
213
+ @overload
214
+ def __get__(self, instance: object, owner: type[Any] | None = None) -> _T: ...
215
+
216
+ def __get__(self, instance: object, owner: type[Any] | None = None) -> _T | Self:
217
+ raise NotImplementedError()
218
+
219
+ def __set_name__(self, owner: type[Any], name: str) -> None: ...
220
+
221
+ # __set__ is not defined at runtime, but @cached_property is designed to be settable
222
+ def __set__(self, instance: object, value: _T) -> None: ...
223
+ else:
224
+ from functools import cached_property as cached_property
225
+
226
+ typed_cached_property = cached_property