hammad-python 0.0.30__py3-none-any.whl → 0.0.32__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 (137) hide show
  1. ham/__init__.py +200 -0
  2. {hammad_python-0.0.30.dist-info → hammad_python-0.0.32.dist-info}/METADATA +6 -32
  3. hammad_python-0.0.32.dist-info/RECORD +6 -0
  4. hammad/__init__.py +0 -84
  5. hammad/_internal.py +0 -256
  6. hammad/_main.py +0 -226
  7. hammad/cache/__init__.py +0 -40
  8. hammad/cache/base_cache.py +0 -181
  9. hammad/cache/cache.py +0 -169
  10. hammad/cache/decorators.py +0 -261
  11. hammad/cache/file_cache.py +0 -80
  12. hammad/cache/ttl_cache.py +0 -74
  13. hammad/cli/__init__.py +0 -33
  14. hammad/cli/animations.py +0 -573
  15. hammad/cli/plugins.py +0 -867
  16. hammad/cli/styles/__init__.py +0 -55
  17. hammad/cli/styles/settings.py +0 -139
  18. hammad/cli/styles/types.py +0 -358
  19. hammad/cli/styles/utils.py +0 -634
  20. hammad/data/__init__.py +0 -90
  21. hammad/data/collections/__init__.py +0 -49
  22. hammad/data/collections/collection.py +0 -326
  23. hammad/data/collections/indexes/__init__.py +0 -37
  24. hammad/data/collections/indexes/qdrant/__init__.py +0 -1
  25. hammad/data/collections/indexes/qdrant/index.py +0 -723
  26. hammad/data/collections/indexes/qdrant/settings.py +0 -94
  27. hammad/data/collections/indexes/qdrant/utils.py +0 -210
  28. hammad/data/collections/indexes/tantivy/__init__.py +0 -1
  29. hammad/data/collections/indexes/tantivy/index.py +0 -426
  30. hammad/data/collections/indexes/tantivy/settings.py +0 -40
  31. hammad/data/collections/indexes/tantivy/utils.py +0 -176
  32. hammad/data/configurations/__init__.py +0 -35
  33. hammad/data/configurations/configuration.py +0 -564
  34. hammad/data/models/__init__.py +0 -50
  35. hammad/data/models/extensions/__init__.py +0 -4
  36. hammad/data/models/extensions/pydantic/__init__.py +0 -42
  37. hammad/data/models/extensions/pydantic/converters.py +0 -759
  38. hammad/data/models/fields.py +0 -546
  39. hammad/data/models/model.py +0 -1078
  40. hammad/data/models/utils.py +0 -280
  41. hammad/data/sql/__init__.py +0 -24
  42. hammad/data/sql/database.py +0 -576
  43. hammad/data/sql/types.py +0 -127
  44. hammad/data/types/__init__.py +0 -75
  45. hammad/data/types/file.py +0 -431
  46. hammad/data/types/multimodal/__init__.py +0 -36
  47. hammad/data/types/multimodal/audio.py +0 -200
  48. hammad/data/types/multimodal/image.py +0 -182
  49. hammad/data/types/text.py +0 -1308
  50. hammad/formatting/__init__.py +0 -33
  51. hammad/formatting/json/__init__.py +0 -27
  52. hammad/formatting/json/converters.py +0 -158
  53. hammad/formatting/text/__init__.py +0 -63
  54. hammad/formatting/text/converters.py +0 -723
  55. hammad/formatting/text/markdown.py +0 -131
  56. hammad/formatting/yaml/__init__.py +0 -26
  57. hammad/formatting/yaml/converters.py +0 -5
  58. hammad/genai/__init__.py +0 -217
  59. hammad/genai/a2a/__init__.py +0 -32
  60. hammad/genai/a2a/workers.py +0 -552
  61. hammad/genai/agents/__init__.py +0 -59
  62. hammad/genai/agents/agent.py +0 -1973
  63. hammad/genai/agents/run.py +0 -1024
  64. hammad/genai/agents/types/__init__.py +0 -42
  65. hammad/genai/agents/types/agent_context.py +0 -13
  66. hammad/genai/agents/types/agent_event.py +0 -128
  67. hammad/genai/agents/types/agent_hooks.py +0 -220
  68. hammad/genai/agents/types/agent_messages.py +0 -31
  69. hammad/genai/agents/types/agent_response.py +0 -125
  70. hammad/genai/agents/types/agent_stream.py +0 -327
  71. hammad/genai/graphs/__init__.py +0 -125
  72. hammad/genai/graphs/_utils.py +0 -190
  73. hammad/genai/graphs/base.py +0 -1828
  74. hammad/genai/graphs/plugins.py +0 -316
  75. hammad/genai/graphs/types.py +0 -638
  76. hammad/genai/models/__init__.py +0 -1
  77. hammad/genai/models/embeddings/__init__.py +0 -43
  78. hammad/genai/models/embeddings/model.py +0 -226
  79. hammad/genai/models/embeddings/run.py +0 -163
  80. hammad/genai/models/embeddings/types/__init__.py +0 -37
  81. hammad/genai/models/embeddings/types/embedding_model_name.py +0 -75
  82. hammad/genai/models/embeddings/types/embedding_model_response.py +0 -76
  83. hammad/genai/models/embeddings/types/embedding_model_run_params.py +0 -66
  84. hammad/genai/models/embeddings/types/embedding_model_settings.py +0 -47
  85. hammad/genai/models/language/__init__.py +0 -57
  86. hammad/genai/models/language/model.py +0 -1098
  87. hammad/genai/models/language/run.py +0 -878
  88. hammad/genai/models/language/types/__init__.py +0 -40
  89. hammad/genai/models/language/types/language_model_instructor_mode.py +0 -47
  90. hammad/genai/models/language/types/language_model_messages.py +0 -28
  91. hammad/genai/models/language/types/language_model_name.py +0 -239
  92. hammad/genai/models/language/types/language_model_request.py +0 -127
  93. hammad/genai/models/language/types/language_model_response.py +0 -217
  94. hammad/genai/models/language/types/language_model_response_chunk.py +0 -56
  95. hammad/genai/models/language/types/language_model_settings.py +0 -89
  96. hammad/genai/models/language/types/language_model_stream.py +0 -600
  97. hammad/genai/models/language/utils/__init__.py +0 -28
  98. hammad/genai/models/language/utils/requests.py +0 -421
  99. hammad/genai/models/language/utils/structured_outputs.py +0 -135
  100. hammad/genai/models/model_provider.py +0 -4
  101. hammad/genai/models/multimodal.py +0 -47
  102. hammad/genai/models/reranking.py +0 -26
  103. hammad/genai/types/__init__.py +0 -1
  104. hammad/genai/types/base.py +0 -215
  105. hammad/genai/types/history.py +0 -290
  106. hammad/genai/types/tools.py +0 -507
  107. hammad/logging/__init__.py +0 -35
  108. hammad/logging/decorators.py +0 -834
  109. hammad/logging/logger.py +0 -1018
  110. hammad/mcp/__init__.py +0 -53
  111. hammad/mcp/client/__init__.py +0 -35
  112. hammad/mcp/client/client.py +0 -624
  113. hammad/mcp/client/client_service.py +0 -400
  114. hammad/mcp/client/settings.py +0 -178
  115. hammad/mcp/servers/__init__.py +0 -26
  116. hammad/mcp/servers/launcher.py +0 -1161
  117. hammad/runtime/__init__.py +0 -32
  118. hammad/runtime/decorators.py +0 -142
  119. hammad/runtime/run.py +0 -299
  120. hammad/service/__init__.py +0 -49
  121. hammad/service/create.py +0 -527
  122. hammad/service/decorators.py +0 -283
  123. hammad/types.py +0 -288
  124. hammad/typing/__init__.py +0 -435
  125. hammad/web/__init__.py +0 -43
  126. hammad/web/http/__init__.py +0 -1
  127. hammad/web/http/client.py +0 -944
  128. hammad/web/models.py +0 -275
  129. hammad/web/openapi/__init__.py +0 -1
  130. hammad/web/openapi/client.py +0 -740
  131. hammad/web/search/__init__.py +0 -1
  132. hammad/web/search/client.py +0 -1023
  133. hammad/web/utils.py +0 -472
  134. hammad_python-0.0.30.dist-info/RECORD +0 -135
  135. {hammad → ham}/py.typed +0 -0
  136. {hammad_python-0.0.30.dist-info → hammad_python-0.0.32.dist-info}/WHEEL +0 -0
  137. {hammad_python-0.0.30.dist-info → hammad_python-0.0.32.dist-info}/licenses/LICENSE +0 -0
hammad/_main.py DELETED
@@ -1,226 +0,0 @@
1
- """hammad._main"""
2
-
3
-
4
- class to:
5
- """Namespace for converters that can be used to convert objects to various formats.
6
-
7
- The `to` class provides a collection of converters that can be used to convert objects
8
- to various formats, such as pydantic models, text, markdown, json, and more.
9
- """
10
-
11
- # ! CONVERTERS
12
- from .data import (
13
- convert_to_pydantic_field as pydantic_field,
14
- convert_to_pydantic_model as pydantic_model,
15
- )
16
- from .data.types import (
17
- convert_to_base_text as text,
18
- convert_to_simple_text as simple_text,
19
- convert_to_code_section as code_section,
20
- convert_to_schema_section as schema_section,
21
- convert_to_output_instructions as output_instructions,
22
- )
23
- from .formatting.json import (
24
- convert_to_json_schema as json_schema,
25
- )
26
- from .formatting.text import (
27
- convert_to_text as markdown,
28
- )
29
-
30
-
31
- class fn:
32
- """Namespace for decorators that can be used to modify functions, methods, and classes.
33
-
34
- The `fn` class provides a collection of decorators that can be used to modify functions,
35
- methods, and classes in various ways, such as caching results, tracing function calls,
36
- and validating input parameters.
37
- """
38
-
39
- # ! DECORATORS
40
- from .cache import cached, auto_cached
41
- from .logging import trace, trace_cls, trace_function, trace_http
42
- from .data.models import validator
43
- from .runtime import (
44
- sequentialize_function as sequentialize,
45
- parallelize_function as parallelize,
46
- run_with_retry as retry,
47
- )
48
- from .service import serve, serve_mcp
49
-
50
-
51
- class new:
52
- """Namespace for factory functions that create new objects, models, services, and clients.
53
-
54
- The `new` class provides convenient access to a variety of factory functions for creating
55
- commonly used objects in the hammad ecosystem, such as caches, collections, databases,
56
- models, loggers, agents, services, and web clients.
57
-
58
- Example usage:
59
- cache = new.cache(...)
60
- collection = new.collection(...)
61
- model = new.model(...)
62
- logger = new.logger(...)
63
- agent = new.agent(...)
64
- service = new.service(...)
65
- http_client = new.http_client(...)
66
- """
67
-
68
- # ! FACTORIES
69
- from .cache import (
70
- create_cache as cache,
71
- )
72
- from .data import (
73
- create_collection as collection,
74
- create_database as database,
75
- create_model as model,
76
- )
77
- from .logging import create_logger as logger
78
- from .genai import (
79
- create_agent as agent,
80
- create_embedding_model as embedding_model,
81
- create_language_model as language_model,
82
- )
83
- from .service import (
84
- create_service as service,
85
- async_create_service as async_service,
86
- )
87
- from .mcp import (
88
- MCPClient as mcp_client,
89
- )
90
- from .web import (
91
- create_http_client as http_client,
92
- create_openapi_client as openapi_client,
93
- create_search_client as search_client,
94
- )
95
-
96
-
97
- class run:
98
- """Centeral namespace for 'one-off' runners, or functions that can be
99
- executed directly, and standalone."""
100
-
101
- # ! RUNNERS
102
- from .genai import (
103
- run_agent as agent,
104
- run_agent_iter as agent_iter,
105
- run_embedding_model as embedding_model,
106
- run_image_edit_model as image_edit_model,
107
- run_image_generation_model as image_generation_model,
108
- run_image_variation_model as image_variation_model,
109
- run_language_model as language_model,
110
- run_reranking_model as reranking_model,
111
- run_transcription_model as transcription_model,
112
- run_tts_model as text_to_speech_model,
113
- )
114
- from .mcp import (
115
- launch_mcp_servers as mcp_servers,
116
- )
117
- from .web import (
118
- run_news_search as news_search,
119
- run_web_search as web_search,
120
- run_web_request as web_request,
121
- )
122
-
123
-
124
- class read:
125
- """Namespace for various resource, URL or other file-type readers."""
126
-
127
- from .data.configurations import (
128
- read_configuration_from_dotenv as configuration_from_dotenv,
129
- read_configuration_from_file as configuration_from_file,
130
- read_configuration_from_url as configuration_from_url,
131
- read_configuration_from_os_prefix as configuration_from_os_prefix,
132
- read_configuration_from_os_vars as configuration_from_os_vars,
133
- )
134
- from .data.types import (
135
- read_file_from_bytes as file_from_bytes,
136
- read_file_from_path as file_from_path,
137
- read_file_from_url as file_from_url,
138
- read_audio_from_path as audio_from_path,
139
- read_audio_from_url as audio_from_url,
140
- read_image_from_path as image_from_path,
141
- read_image_from_url as image_from_url,
142
- )
143
- from .web import (
144
- read_web_page as web_page,
145
- read_web_pages as web_pages,
146
- extract_web_page_links as extract_links,
147
- )
148
-
149
-
150
- class settings:
151
- """Namespace class for all settings definitions within the ecosystem. This is an
152
- easy way to find the configuration settings for the component you are intending
153
- to use."""
154
-
155
- # NOTE:
156
- # these are attached to the 'core/builtin' extensions imported at the very top
157
- # hence the weird very very literal names
158
- from .cli import (
159
- CLIStyleLiveSettings as live,
160
- CLIStyleBackgroundSettings as bg,
161
- CLIStyleRenderableSettings as style,
162
- )
163
-
164
- from .data import (
165
- QdrantCollectionIndexSettings as qdrant,
166
- QdrantCollectionIndexQuerySettings as qdrant_query,
167
- TantivyCollectionIndexSettings as tantivy,
168
- TantivyCollectionIndexQuerySettings as tantivy_query,
169
- )
170
- from .logging.logger import LoggerLevelSettings as logger_level
171
- from .genai import (
172
- AgentSettings as agent,
173
- LanguageModelSettings as language_model,
174
- EmbeddingModelSettings as embedding_model,
175
- )
176
- from .mcp import (
177
- MCPClientSseSettings as mcp_client_sse,
178
- MCPClientStdioSettings as mcp_client_stdio,
179
- MCPClientStreamableHttpSettings as mcp_client_streamable_http,
180
- MCPServerSseSettings as mcp_server_sse,
181
- MCPServerStdioSettings as mcp_server_stdio,
182
- MCPServerStreamableHttpSettings as mcp_server_streamable_http,
183
- )
184
-
185
-
186
- __all__ = (
187
- # hammad.cache
188
- "cached",
189
- # hammad.cli
190
- "print",
191
- "input",
192
- "animate",
193
- # hammad.logging
194
- "logger",
195
- # hammad.genai
196
- "BaseGraph",
197
- "plugin",
198
- "action",
199
- "agent",
200
- "llm",
201
- "tool",
202
- # hammad.data.collections
203
- "collection",
204
- # hammad.formatting.text
205
- "markdown",
206
- # hammad.mcp
207
- "launch_mcp_servers",
208
- # hammad.service
209
- "serve",
210
- "serve_mcp",
211
- # hammad.web
212
- "web_search",
213
- "web_request",
214
- # hammad.to
215
- "to",
216
- # hammad.fn
217
- "fn",
218
- # hammad.new
219
- "new",
220
- # hammad.run
221
- "run",
222
- # hammad.read
223
- "read",
224
- # hammad.settings
225
- "settings",
226
- )
hammad/cache/__init__.py DELETED
@@ -1,40 +0,0 @@
1
- """hammad.cache"""
2
-
3
- from typing import TYPE_CHECKING
4
- from .._internal import create_getattr_importer
5
-
6
-
7
- if TYPE_CHECKING:
8
- from .base_cache import BaseCache, CacheParams, CacheReturn, CacheType
9
- from .file_cache import FileCache, FileCacheLocation
10
- from .ttl_cache import TTLCache
11
- from .cache import Cache, create_cache
12
- from .decorators import cached, auto_cached, clear_decorator_cache
13
-
14
-
15
- __all__ = (
16
- # hammad.performance.cache.base_cache
17
- "BaseCache",
18
- "CacheParams",
19
- "CacheReturn",
20
- "CacheType",
21
- # hammad.performance.cache.file_cache
22
- "FileCache",
23
- "FileCacheLocation",
24
- # hammad.performance.cache.ttl_cache
25
- "TTLCache",
26
- # hammad.performance.cache.cache
27
- "Cache",
28
- "create_cache",
29
- # hammad.performance.cache.decorators
30
- "cached",
31
- "auto_cached",
32
- "clear_decorator_cache",
33
- )
34
-
35
-
36
- __getattr__ = create_getattr_importer(__all__)
37
-
38
-
39
- def __dir__() -> list[str]:
40
- return sorted(__all__)
@@ -1,181 +0,0 @@
1
- """hammad.cache.base_cache"""
2
-
3
- from dataclasses import dataclass
4
- import hashlib
5
- import inspect
6
- from typing import Any, Literal, ParamSpec, TypeAlias, TypeVar, get_args
7
-
8
- __all__ = (
9
- "BaseCache",
10
- "CacheType",
11
- "CacheParams",
12
- "CacheReturn",
13
- )
14
-
15
-
16
- CacheType: TypeAlias = Literal["ttl", "file"]
17
- """Type of caches that can be created using `hammad`.
18
-
19
- - `"ttl"`: Time-to-live cache.
20
- - `"file"`: File-based cache.
21
- """
22
-
23
- CacheParams = ParamSpec("CacheParams")
24
- """Parameter specification for cache functions."""
25
-
26
- CacheReturn = TypeVar("CacheReturn")
27
- """Return type for cache functions."""
28
-
29
-
30
- @dataclass
31
- class BaseCache:
32
- """Base class for all caches created using `hammad`."""
33
-
34
- type: CacheType
35
- """Type of cache."""
36
-
37
- def __post_init__(self) -> None:
38
- """Post-initialization hook."""
39
- if self.type not in get_args(CacheType):
40
- raise ValueError(f"Invalid cache type: {self.type}")
41
-
42
- def __contains__(self, key: str) -> bool:
43
- """Check if key exists in cache."""
44
- raise NotImplementedError("Subclasses must implement __contains__")
45
-
46
- def __getitem__(self, key: str) -> Any:
47
- """Get value for key."""
48
- raise NotImplementedError("Subclasses must implement __getitem__")
49
-
50
- def __setitem__(self, key: str, value: Any) -> None:
51
- """Set value for key."""
52
- raise NotImplementedError("Subclasses must implement __setitem__")
53
-
54
- def get(self, key: str, default: Any = None) -> Any:
55
- """Get value with default if key doesn't exist."""
56
- try:
57
- return self[key]
58
- except KeyError:
59
- return default
60
-
61
- def clear(self) -> None:
62
- """Clear all cached items."""
63
- raise NotImplementedError("Subclasses must implement clear")
64
-
65
- def make_hashable(self, obj: Any) -> str:
66
- """
67
- Convert any object to a stable hash string.
68
-
69
- Uses SHA-256 to generate consistent hash representations.
70
- Handles nested structures recursively.
71
-
72
- Args:
73
- obj: Object to hash
74
-
75
- Returns:
76
- Hexadecimal hash string
77
- """
78
-
79
- def _hash_obj(data: Any) -> str:
80
- """Internal recursive hashing function with memoization."""
81
- # Handle None first
82
- if data is None:
83
- return "null"
84
-
85
- if isinstance(data, bool):
86
- return f"bool:{data}"
87
- elif isinstance(data, int):
88
- return f"int:{data}"
89
- elif isinstance(data, float):
90
- if data != data: # NaN
91
- return "float:nan"
92
- elif data == float("inf"):
93
- return "float:inf"
94
- elif data == float("-inf"):
95
- return "float:-inf"
96
- else:
97
- return f"float:{data}"
98
- elif isinstance(data, str):
99
- return f"str:{data}"
100
- elif isinstance(data, bytes):
101
- return f"bytes:{data.hex()}"
102
-
103
- # Handle collections
104
- elif isinstance(data, (list, tuple)):
105
- collection_type = "list" if isinstance(data, list) else "tuple"
106
- items = [_hash_obj(item) for item in data]
107
- return f"{collection_type}:[{','.join(items)}]"
108
-
109
- elif isinstance(data, set):
110
- try:
111
- sorted_items = sorted(data, key=lambda x: str(x))
112
- except TypeError:
113
- sorted_items = sorted(
114
- data, key=lambda x: (type(x).__name__, str(x))
115
- )
116
- items = [_hash_obj(item) for item in sorted_items]
117
- return f"set:{{{','.join(items)}}}"
118
-
119
- elif isinstance(data, dict):
120
- try:
121
- sorted_items = sorted(data.items(), key=lambda x: str(x[0]))
122
- except TypeError:
123
- # Fallback for non-comparable keys
124
- sorted_items = sorted(
125
- data.items(), key=lambda x: (type(x[0]).__name__, str(x[0]))
126
- )
127
- pairs = [f"{_hash_obj(k)}:{_hash_obj(v)}" for k, v in sorted_items]
128
- return f"dict:{{{','.join(pairs)}}}"
129
-
130
- elif isinstance(data, type):
131
- module = getattr(data, "__module__", "builtins")
132
- qualname = getattr(data, "__qualname__", data.__name__)
133
- return f"type:{module}.{qualname}"
134
-
135
- elif callable(data):
136
- module = getattr(data, "__module__", "unknown")
137
- qualname = getattr(
138
- data, "__qualname__", getattr(data, "__name__", "unknown_callable")
139
- )
140
-
141
- try:
142
- source = inspect.getsource(data)
143
- normalized_source = " ".join(source.split())
144
- return f"callable:{module}.{qualname}:{hash(normalized_source)}"
145
- except (OSError, TypeError, IndentationError):
146
- return f"callable:{module}.{qualname}"
147
-
148
- elif hasattr(data, "__dict__"):
149
- class_info = (
150
- f"{data.__class__.__module__}.{data.__class__.__qualname__}"
151
- )
152
- obj_dict = {"__class__": class_info, **data.__dict__}
153
- return f"object:{_hash_obj(obj_dict)}"
154
-
155
- elif hasattr(data, "__slots__"):
156
- class_info = (
157
- f"{data.__class__.__module__}.{data.__class__.__qualname__}"
158
- )
159
- slot_dict = {
160
- slot: getattr(data, slot, None)
161
- for slot in data.__slots__
162
- if hasattr(data, slot)
163
- }
164
- obj_dict = {"__class__": class_info, **slot_dict}
165
- return f"slotted_object:{_hash_obj(obj_dict)}"
166
-
167
- else:
168
- try:
169
- repr_str = repr(data)
170
- return f"repr:{type(data).__name__}:{repr_str}"
171
- except Exception:
172
- # Ultimate fallback
173
- return f"unknown:{type(data).__name__}:{id(data)}"
174
-
175
- # Generate the hash representation
176
- hash_representation = _hash_obj(obj)
177
-
178
- # Create final SHA-256 hash
179
- return hashlib.sha256(
180
- hash_representation.encode("utf-8", errors="surrogatepass")
181
- ).hexdigest()
hammad/cache/cache.py DELETED
@@ -1,169 +0,0 @@
1
- """hammad.cache.cache"""
2
-
3
- from typing import (
4
- overload,
5
- TYPE_CHECKING,
6
- Literal,
7
- Optional,
8
- Any,
9
- Union,
10
- get_args,
11
- )
12
- from pathlib import Path
13
-
14
- from .base_cache import BaseCache, CacheType
15
- from .file_cache import FileCache, FileCacheLocation
16
- from .ttl_cache import TTLCache
17
-
18
-
19
- __all__ = ("Cache", "create_cache")
20
-
21
-
22
- class Cache:
23
- """
24
- Helper factory class for creating cache instances.
25
-
26
- Example usage:
27
- ttl_cache = Cache(type="ttl", maxsize=100, ttl=60)
28
- file_cache = Cache(type="file", location="cache.pkl")
29
- """
30
-
31
- @overload
32
- def __new__(
33
- cls,
34
- type: Literal["ttl"] = "ttl",
35
- *,
36
- maxsize: Optional[int] = None,
37
- ttl: Optional[int] = None,
38
- ) -> "TTLCache":
39
- """
40
- Create a new TTL (Time To Live) cache instance.
41
-
42
- Args:
43
- type: The type of cache to create.
44
- maxsize: The maximum number of items to store in the cache.
45
- ttl: The time to live for items in the cache.
46
-
47
- Returns:
48
- A new TTL cache instance.
49
- """
50
- ...
51
-
52
- @overload
53
- def __new__(
54
- cls, type: Literal["file"], *, location: Optional["FileCacheLocation"] = None
55
- ) -> "FileCache":
56
- """
57
- Create a new file cache instance.
58
-
59
- Args:
60
- type: The type of cache to create.
61
- location: The directory to store the cache files.
62
-
63
- Returns:
64
- A new disk cache instance.
65
- """
66
- ...
67
-
68
- def __new__(cls, type: "CacheType" = "ttl", **kwargs: Any) -> "BaseCache":
69
- """
70
- Create a new cache instance.
71
- """
72
- if type == "ttl":
73
- from .ttl_cache import TTLCache
74
-
75
- valid_ttl_params = {"maxsize", "ttl"}
76
- ttl_constructor_kwargs = {
77
- k: v
78
- for k, v in kwargs.items()
79
- if k in valid_ttl_params and v is not None
80
- }
81
- return TTLCache(type=type, **ttl_constructor_kwargs)
82
- elif type == "file":
83
- from .file_cache import FileCache
84
-
85
- valid_file_params = {"location"}
86
- file_constructor_kwargs = {
87
- k: v
88
- for k, v in kwargs.items()
89
- if k in valid_file_params and v is not None
90
- }
91
- return FileCache(type=type, **file_constructor_kwargs)
92
- else:
93
- supported_types_tuple = get_args(CacheType)
94
- raise ValueError(
95
- f"Unsupported cache type: {type}. Supported types are: {supported_types_tuple}"
96
- )
97
-
98
-
99
- # Factory
100
-
101
-
102
- @overload
103
- def create_cache(
104
- type: Literal["ttl"], *, maxsize: int = 128, ttl: Optional[float] = None
105
- ) -> "TTLCache": ...
106
-
107
-
108
- @overload
109
- def create_cache(
110
- type: Literal["file"],
111
- *,
112
- location: Optional["FileCacheLocation"] = None,
113
- maxsize: int = 128,
114
- ) -> "FileCache": ...
115
-
116
-
117
- @overload
118
- def create_cache(type: "CacheType", **kwargs: Any) -> "BaseCache": ...
119
-
120
-
121
- def create_cache(type: "CacheType", **kwargs: Any) -> "BaseCache":
122
- """
123
- Factory function to create cache instances of different types.
124
-
125
- Args:
126
- type: The type of cache to create. Can be "ttl" or "file".
127
- **kwargs: Additional keyword arguments specific to the cache type.
128
-
129
- Returns:
130
- A cache instance of the specified type.
131
-
132
- Raises:
133
- ValueError: If an unsupported cache type is provided.
134
-
135
- Examples:
136
- ```python
137
- # Create a TTL cache with custom settings
138
- ttl_cache = create_cache("ttl", maxsize=256, ttl=300)
139
-
140
- # Create a file cache with custom location
141
- file_cache = create_cache("file", location="/tmp/my_cache", maxsize=1000)
142
- ```
143
- """
144
- if type == "ttl":
145
- from .ttl_cache import TTLCache
146
-
147
- maxsize = kwargs.pop("maxsize", 128)
148
- ttl = kwargs.pop("ttl", None)
149
- if kwargs:
150
- raise TypeError(
151
- f"Unexpected keyword arguments for TTL cache: {list(kwargs.keys())}"
152
- )
153
- return TTLCache(maxsize=maxsize, ttl=ttl)
154
- elif type == "file":
155
- from .file_cache import FileCache
156
-
157
- location = kwargs.pop("location", None)
158
- # FileCache doesn't support maxsize, so we just ignore it
159
- kwargs.pop("maxsize", None)
160
- if kwargs:
161
- raise TypeError(
162
- f"Unexpected keyword arguments for file cache: {list(kwargs.keys())}"
163
- )
164
- return FileCache(location=location, type=type)
165
- else:
166
- valid_types = get_args("CacheType")
167
- raise ValueError(
168
- f"Unsupported cache type: {type}. Valid types are: {valid_types}"
169
- )