Title: performance issue / optimization: response parsing is unnecessarily slow · Issue #201 · square/square-python-sdk · GitHub
Open Graph Title: performance issue / optimization: response parsing is unnecessarily slow · Issue #201 · square/square-python-sdk
X Title: performance issue / optimization: response parsing is unnecessarily slow · Issue #201 · square/square-python-sdk
Description: Summary Response parsing is unnecessarily slow and CPU bound, due to repeated calls to get_type_hints. client.catalog.search(limit=1000, include_related_objects=True) returns in under 3s, then the SDK spends ~7s of CPU building the respo...
Open Graph Description: Summary Response parsing is unnecessarily slow and CPU bound, due to repeated calls to get_type_hints. client.catalog.search(limit=1000, include_related_objects=True) returns in under 3s, then the ...
X Description: Summary Response parsing is unnecessarily slow and CPU bound, due to repeated calls to get_type_hints. client.catalog.search(limit=1000, include_related_objects=True) returns in under 3s, then the ...
Opengraph URL: https://github.com/square/square-python-sdk/issues/201
X: @github
Domain: github.com
IPv4 address: 140.82.114.4
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"performance issue / optimization: response parsing is unnecessarily slow","articleBody":"## Summary\n\nResponse parsing is unnecessarily slow and CPU bound, due to repeated calls to `get_type_hints`.\n\n`client.catalog.search(limit=1000, include_related_objects=True)` returns in under 3s, then the SDK spends ~7s of CPU building the response models. For a per-SKU catalog of a few thousand objects, parsing dominates the call.\n\nProfiling 200 objects shows 13,000 calls to `typing_extensions.get_type_hints`, about 65 per catalog object, and nearly all of the wall time under them. The chain is:\n\n1. `CatalogObject.item_data` is `Optional[CatalogItem]`, an undiscriminated union, so `construct_type` routes it through [`_convert_undiscriminated_union_type`](https://github.com/square/square-python-sdk/blob/42a14b077c208817cc8bec118e38066ac01a4d07/src/square/core/unchecked_base_model.py#L153), which trial-parses each member with [`parse_obj_as`](https://github.com/square/square-python-sdk/blob/42a14b077c208817cc8bec118e38066ac01a4d07/src/square/core/unchecked_base_model.py#L174).\n2. [`parse_obj_as`](https://github.com/square/square-python-sdk/blob/42a14b077c208817cc8bec118e38066ac01a4d07/src/square/core/pydantic_utilities.py#L256) de-aliases the input through `convert_and_respect_annotation_metadata`, which recurses the annotation tree.\n3. Every level of that recursion calls [`get_type_hints` in `_convert_mapping`](https://github.com/square/square-python-sdk/blob/42a14b077c208817cc8bec118e38066ac01a4d07/src/square/core/serialization.py#L164). The result depends only on the type, but it is recomputed for every object. The generated models use `from __future__ import annotations`, so each call compiles and evaluates every forward reference again.\n\nMemoizing `get_type_hints` by type brings the same page from 6.5s to 0.7s with identical output.\n\n## Reproduction\n\nNo network needed. Builds a 1,000-item search response and parses it the way the client does.\n\n```python\nimport functools\nimport time\n\nimport typing_extensions\nfrom square.core import serialization\nfrom square.core import unchecked_base_model as ubm\nfrom square.types.search_catalog_objects_response import SearchCatalogObjectsResponse\n\n\ndef item(i):\n variations = [\n {\n \"type\": \"ITEM_VARIATION\",\n \"id\": f\"V{i}_{j}\",\n \"item_variation_data\": {\n \"item_id\": f\"I{i}\",\n \"name\": f\"Size {j}\",\n \"pricing_type\": \"FIXED_PRICING\",\n \"price_money\": {\"amount\": 500, \"currency\": \"USD\"},\n },\n }\n for j in range(3)\n ]\n return {\"type\": \"ITEM\", \"id\": f\"I{i}\", \"item_data\": {\"name\": f\"Item {i}\", \"variations\": variations}}\n\n\npage = {\n \"objects\": [item(i) for i in range(1000)],\n \"related_objects\": [\n {\"type\": \"IMAGE\", \"id\": f\"IMG{i}\", \"image_data\": {\"url\": \"https://example.com/1.png\"}} for i in range(1000)\n ],\n}\n\n\ndef parse():\n start = time.perf_counter()\n ubm.construct_type(type_=SearchCatalogObjectsResponse, object_=page)\n return time.perf_counter() - start\n\n\nprint(f\"unpatched: {parse():.1f}s\")\n\ncached = functools.cache(lambda t, extras: typing_extensions.get_type_hints(t, include_extras=extras))\n\n\nclass Shim:\n def __getattr__(self, name):\n return getattr(typing_extensions, name)\n\n @staticmethod\n def get_type_hints(obj, globalns=None, localns=None, include_extras=False):\n return cached(obj, include_extras)\n\n\nserialization.typing_extensions = Shim()\nprint(f\"get_type_hints memoized: {parse():.1f}s\")\n```\n\nOutput on my machine:\n\n```\nunpatched: 6.5s\nget_type_hints memoized: 0.7s\n```\n\n## Suggested fix\n\nCache `get_type_hints` per type inside `serialization.py`, for example with `functools.lru_cache` around the three call sites. A type's hints do not change at runtime, so the cache is safe and unbounded by object count. Alternatively, `_convert_undiscriminated_union_type` could construct an `Optional[BaseModel]` member directly instead of validating it through `parse_obj_as`.\n\n## Environment\n\n* **SDK:** squareup 46.0.0.20260916\n* **Python:** 3.14\n\n## Related\n\n[`_convert_union_type`](https://github.com/square/square-python-sdk/blob/42a14b077c208817cc8bec118e38066ac01a4d07/src/square/core/unchecked_base_model.py#L236) reads `inner_type.__fields__`, which pydantic 2 deprecates with a `PydanticDeprecatedSince20` warning on every discriminated object. Under pydantic 3 that attribute goes away, the `except Exception` swallows the error, and every `CatalogObject` would fall into the slow undiscriminated path above.\n","author":{"url":"https://github.com/mik3y","@type":"Person","name":"mik3y"},"datePublished":"2026-10-31T20:55:53Z","url":"https://github.com/square/square-python-sdk/issues/201"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:56fbe4b2-f980-301b-13e5-c200ce50c49e |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 80CE:3C538A:F930D5:1554AF2:6B055A3D |
| html-safe-nonce | 379ea1454d4b2ecdc6d7b8bc05db552bfd9a9d940d16e72edacc3a22494edd75 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4MENFOjNDNTM4QTpGOTMwRDU6MTU1NEFGMjo2QjA1NUEzRCIsInZpc2l0b3JfaWQiOiI3MDY3NjE2MTQxOTA0MjcxOTM0IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | ff79ef51760320a7e87f48a53e0cced504006aace4729a1a89df779d548fbd73 |
| hovercard-subject-tag | issue:6139667801 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/square/square-python-sdk/201/issue_layout |
| twitter:image | https://opengraph.githubassets.com/4eb76fd42a91551cf6467c799860aadd91d95307751fdcd71672bebdfd34468d/square/square-python-sdk/issues/201 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/4eb76fd42a91551cf6467c799860aadd91d95307751fdcd71672bebdfd34468d/square/square-python-sdk/issues/201 |
| og:image:alt | Summary Response parsing is unnecessarily slow and CPU bound, due to repeated calls to get_type_hints. client.catalog.search(limit=1000, include_related_objects=True) returns in under 3s, then the ... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | mik3y |
| hostname | github.com |
| expected-hostname | github.com |
| None | a79a02b7e7546ea306864e922ed2103ef4c04fac63168e11c2b2d4d816793080 |
| turbo-cache-control | no-preview |
| go-import | github.com/square/square-python-sdk git https://github.com/square/square-python-sdk.git |
| octolytics-dimension-user_id | 82592 |
| octolytics-dimension-user_login | square |
| octolytics-dimension-repository_id | 199728156 |
| octolytics-dimension-repository_nwo | square/square-python-sdk |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 199728156 |
| octolytics-dimension-repository_network_root_nwo | square/square-python-sdk |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 10dff83edfd4f3617a7792a152d44991587b434c |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
| Server | github.com |
| Content-Type | text/html; charset=utf-8 |
| Cache-Control | max-age=0, private, must-revalidate |
Viewport: width=device-width