Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/redis/utils.py: 42%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

373 statements  

1import datetime 

2import inspect 

3import logging 

4import os 

5import sys 

6import textwrap 

7import threading 

8import warnings 

9import weakref 

10from collections.abc import Callable, Iterable 

11from contextlib import contextmanager 

12from functools import cache, wraps 

13from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, TypeVar, Union 

14 

15from redis.exceptions import DataError 

16from redis.typing import AbsExpiryT, EncodableT, ExpiryT 

17 

18if TYPE_CHECKING: 

19 from redis.client import Redis 

20 

21try: 

22 import hiredis # noqa 

23 

24 # Only support Hiredis >= 3.0: 

25 hiredis_version = hiredis.__version__.split(".") 

26 HIREDIS_AVAILABLE = int(hiredis_version[0]) > 3 or ( 

27 int(hiredis_version[0]) == 3 and int(hiredis_version[1]) >= 2 

28 ) 

29 if not HIREDIS_AVAILABLE: 

30 raise ImportError("hiredis package should be >= 3.2.0") 

31except ImportError: 

32 HIREDIS_AVAILABLE = False 

33 

34try: 

35 import ssl # noqa 

36 

37 SSL_AVAILABLE = True 

38except ImportError: 

39 SSL_AVAILABLE = False 

40 

41try: 

42 import cryptography # noqa 

43 

44 CRYPTOGRAPHY_AVAILABLE = True 

45except ImportError: 

46 CRYPTOGRAPHY_AVAILABLE = False 

47 

48from importlib import metadata 

49 

50# Shared marker for omitted arguments, especially where None is a valid 

51# explicit value. Import this object from redis.utils instead of creating local 

52# sentinels, and compare it by identity only (`is` / `is not`). 

53SENTINEL = object() 

54 

55# Weak values: a context stays cached only while a live connection holds it. 

56_SHARED_SSL_CONTEXTS: "weakref.WeakValueDictionary[Any, ssl.SSLContext]" = ( 

57 weakref.WeakValueDictionary() 

58) 

59_SHARED_SSL_CONTEXTS_LOCK = threading.Lock() 

60 

61 

62def _reset_shared_ssl_contexts_lock() -> None: 

63 # A fork while another thread builds a context would leave the child with a lock 

64 # that nothing can release. 

65 global _SHARED_SSL_CONTEXTS_LOCK 

66 _SHARED_SSL_CONTEXTS_LOCK = threading.Lock() 

67 

68 

69if hasattr(os, "register_at_fork"): 

70 os.register_at_fork(after_in_child=_reset_shared_ssl_contexts_lock) 

71 

72 

73def _file_signature(path: Any) -> tuple[int, int, int, int] | None: 

74 try: 

75 stat = os.stat(path) 

76 except (OSError, TypeError, ValueError): 

77 # Left for the context build to report, as it would without the cache 

78 return None 

79 return stat.st_mtime_ns, stat.st_ctime_ns, stat.st_size, stat.st_ino 

80 

81 

82def get_shared_ssl_context( 

83 build: Callable[[], "ssl.SSLContext"], settings: Any, files: Iterable[Any] 

84) -> "ssl.SSLContext": 

85 """ 

86 Return an SSLContext shared by the connections with the same TLS configuration. 

87 

88 Building a context loads the CA bundle into a new certificate store, which costs 

89 far more memory than the TLS connection using it. 

90 

91 Args: 

92 build: Builds the context when no live one matches. 

93 settings: Hashable values that determine the context. 

94 files: The certificate files and directories the context is loaded from. 

95 They are identified by their timestamps, size and inode, so that a rotated 

96 file is picked up by the next context built for it. The default CA 

97 locations are always included, as is SSLKEYLOGFILE, which 

98 ssl.create_default_context() reads. 

99 """ 

100 defaults = ssl.get_default_verify_paths() 

101 paths = (*files, defaults.cafile, defaults.capath) 

102 key = ( 

103 settings, 

104 os.environ.get("SSLKEYLOGFILE"), 

105 tuple((path, _file_signature(path)) for path in paths), 

106 ) 

107 try: 

108 hash(key) 

109 except (TypeError, ValueError): 

110 # An unhashable setting, such as ssl_ca_data given as a bytearray or a 

111 # writable memoryview 

112 return build() 

113 with _SHARED_SSL_CONTEXTS_LOCK: 

114 context = _SHARED_SSL_CONTEXTS.get(key) 

115 if context is None: 

116 # Built outside the lock, so a slow CA load or ssl_password callback does not 

117 # stall other connects. A build that loses the race is dropped before any 

118 # socket wraps it. 

119 built = build() 

120 with _SHARED_SSL_CONTEXTS_LOCK: 

121 context = _SHARED_SSL_CONTEXTS.get(key) 

122 if context is None: 

123 context = _SHARED_SSL_CONTEXTS[key] = built 

124 return context 

125 

126 

127def from_url(url: str, **kwargs: Any) -> "Redis": 

128 """ 

129 Returns an active Redis client generated from the given database URL. 

130 

131 Will attempt to extract the database id from the path url fragment, if 

132 none is provided. 

133 """ 

134 from redis.client import Redis 

135 

136 return Redis.from_url(url, **kwargs) 

137 

138 

139@contextmanager 

140def pipeline(redis_obj): 

141 p = redis_obj.pipeline() 

142 try: 

143 yield p 

144 p.execute() 

145 finally: 

146 p.reset() 

147 

148 

149def is_os_level_timeout(exc: BaseException) -> bool: 

150 """Tell an OS-level timeout apart from a socket/asyncio timeout. 

151 

152 Since Python 3.10 ``socket.timeout`` and since 3.11 ``asyncio.TimeoutError`` 

153 are the builtin ``TimeoutError``, an ``OSError`` subclass. A timeout the OS 

154 reports on a broken connection (``ETIMEDOUT``, e.g. after a network change) 

155 is therefore caught by the same ``except`` clauses as our own read/write 

156 timeouts, although it means the connection is dead. Only the OS-level error 

157 carries an errno. 

158 """ 

159 return isinstance(exc, OSError) and exc.errno is not None 

160 

161 

162def str_if_bytes(value: Union[str, bytes]) -> str: 

163 return ( 

164 value.decode("utf-8", errors="replace") if isinstance(value, bytes) else value 

165 ) 

166 

167 

168def safe_str(value): 

169 return str(str_if_bytes(value)) 

170 

171 

172def decode_field_value(value, key=None, field_encodings=None): 

173 """Decode a field value respecting optional per-field encoding overrides. 

174 

175 - If *field_encodings* is provided and *key* is in it, the corresponding 

176 encoding is used (``None`` means keep raw bytes). 

177 - Otherwise falls back to :func:`str_if_bytes`. 

178 """ 

179 if not isinstance(value, bytes): 

180 return value 

181 if field_encodings and key is not None and key in field_encodings: 

182 encoding = field_encodings[key] 

183 if encoding is None: 

184 return value 

185 return value.decode(encoding, "replace") 

186 return str_if_bytes(value) 

187 

188 

189def dict_merge(*dicts: Mapping[str, Any]) -> Dict[str, Any]: 

190 """ 

191 Merge all provided dicts into 1 dict. 

192 *dicts : `dict` 

193 dictionaries to merge 

194 """ 

195 merged = {} 

196 

197 for d in dicts: 

198 merged.update(d) 

199 

200 return merged 

201 

202 

203def list_keys_to_dict(key_list, callback): 

204 return dict.fromkeys(key_list, callback) 

205 

206 

207def merge_result(command, res): 

208 """ 

209 Merge all items in `res` into a list. 

210 

211 This command is used when sending a command to multiple nodes 

212 and the result from each node should be merged into a single list. 

213 

214 res : 'dict' 

215 """ 

216 result = set() 

217 

218 for v in res.values(): 

219 for value in v: 

220 result.add(value) 

221 

222 return list(result) 

223 

224 

225def warn_deprecated(name, reason="", version="", stacklevel=2): 

226 import warnings 

227 

228 msg = f"Call to deprecated {name}." 

229 if reason: 

230 msg += f" ({reason})" 

231 if version: 

232 msg += f" -- Deprecated since version {version}." 

233 warnings.warn(msg, category=DeprecationWarning, stacklevel=stacklevel) 

234 

235 

236def deprecated_function(reason="", version="", name=None): 

237 """ 

238 Decorator to mark a function as deprecated. 

239 """ 

240 

241 def decorator(func): 

242 if inspect.iscoroutinefunction(func): 

243 # Create async wrapper for async functions 

244 @wraps(func) 

245 async def async_wrapper(*args, **kwargs): 

246 warn_deprecated(name or func.__name__, reason, version, stacklevel=3) 

247 return await func(*args, **kwargs) 

248 

249 return async_wrapper 

250 else: 

251 # Create regular wrapper for sync functions 

252 @wraps(func) 

253 def wrapper(*args, **kwargs): 

254 warn_deprecated(name or func.__name__, reason, version, stacklevel=3) 

255 return func(*args, **kwargs) 

256 

257 return wrapper 

258 

259 return decorator 

260 

261 

262def warn_deprecated_arg_usage( 

263 arg_name: Union[list, str], 

264 function_name: str, 

265 reason: str = "", 

266 version: str = "", 

267 stacklevel: int = 2, 

268): 

269 import warnings 

270 

271 msg = ( 

272 f"Call to '{function_name}' function with deprecated" 

273 f" usage of input argument/s '{arg_name}'." 

274 ) 

275 if reason: 

276 msg += f" ({reason})" 

277 if version: 

278 msg += f" -- Deprecated since version {version}." 

279 warnings.warn(msg, category=DeprecationWarning, stacklevel=stacklevel) 

280 

281 

282C = TypeVar("C", bound=Callable) 

283 

284 

285def _get_filterable_args( 

286 func: Callable, args: tuple, kwargs: dict, allowed_args: tuple = () 

287) -> dict: 

288 """ 

289 Extract arguments from function call that should be checked for deprecation/experimental warnings. 

290 Excludes 'self' and any explicitly allowed args. 

291 """ 

292 arg_names = func.__code__.co_varnames[: func.__code__.co_argcount] 

293 filterable_args = dict(zip(arg_names, args)) 

294 filterable_args.update(kwargs) 

295 filterable_args.pop("self", None) 

296 if allowed_args: 

297 for allowed_arg in allowed_args: 

298 filterable_args.pop(allowed_arg, None) 

299 return filterable_args 

300 

301 

302_DictKeys = type({}.keys()) 

303 

304 

305def _get_warn_check( 

306 func: Callable, args_to_warn: tuple, allowed_args: tuple = () 

307) -> tuple[int, Callable[[Any, frozenset], bool], frozenset]: 

308 """ 

309 Build the call-time pre-check for the deprecated/experimental args decorators. 

310 Returns the lowest positional index whose presence may need a warning 

311 (sys.maxsize if none), and a dict_keys operation with the names it is 

312 applied to: keys_ok(kwargs.keys(), names) is True when the passed kwargs 

313 need no warning. 

314 """ 

315 pos_names = func.__code__.co_varnames[: func.__code__.co_argcount] 

316 if "*" in args_to_warn: 

317 names = frozenset(allowed_args) | {"self"} 

318 min_idx = next( 

319 (i for i, name in enumerate(pos_names) if name not in names), 

320 sys.maxsize, 

321 ) 

322 return min_idx, _DictKeys.__le__, names 

323 names = frozenset(args_to_warn) - frozenset(allowed_args) - {"self"} 

324 min_idx = next( 

325 (i for i, name in enumerate(pos_names) if name in names), sys.maxsize 

326 ) 

327 return min_idx, _DictKeys.isdisjoint, names 

328 

329 

330def deprecated_args( 

331 args_to_warn: Optional[List[str]] = None, 

332 allowed_args: Optional[List[str]] = None, 

333 reason: str = "", 

334 version: str = "", 

335) -> Callable[[C], C]: 

336 """ 

337 Decorator to mark specified args of a function as deprecated. 

338 If '*' is in args_to_warn, all arguments will be marked as deprecated. 

339 """ 

340 warned = tuple(args_to_warn) if args_to_warn is not None else ("*",) 

341 allowed = tuple(allowed_args) if allowed_args is not None else () 

342 

343 def decorator(func: C) -> C: 

344 # Stacked @deprecated_args decorators collapse into one wrapper, so a 

345 # call pays for a single extra frame however many layers there are. 

346 # Layers are kept outermost first, which is the order they warn in. 

347 layers = ((warned, allowed, reason, version),) 

348 stacked = getattr(func, "_deprecated_args_layers", None) 

349 # functools.wraps copies the tag onto any decorator wrapping ours, so 

350 # merge only when func is our wrapper of the recorded target. 

351 if stacked is not None and getattr(func, "__wrapped__", None) is stacked[0]: 

352 func = stacked[0] 

353 layers += stacked[1] 

354 checks = _get_layer_checks(func, layers) 

355 min_idx, keys_ok, names = _merge_warn_checks(checks) 

356 

357 if inspect.iscoroutinefunction(func): 

358 

359 @wraps(func) 

360 async def async_wrapper(*args, **kwargs): 

361 if len(args) > min_idx or ( 

362 kwargs and not keys_ok(kwargs.keys(), names) 

363 ): 

364 _check_deprecated_layers(func, checks, args, kwargs) 

365 return await func(*args, **kwargs) 

366 

367 async_wrapper._deprecated_args_layers = (func, layers) 

368 return async_wrapper 

369 else: 

370 

371 @wraps(func) 

372 def wrapper(*args, **kwargs): 

373 if len(args) > min_idx or ( 

374 kwargs and not keys_ok(kwargs.keys(), names) 

375 ): 

376 _check_deprecated_layers(func, checks, args, kwargs) 

377 return func(*args, **kwargs) 

378 

379 wrapper._deprecated_args_layers = (func, layers) 

380 return wrapper 

381 

382 return decorator 

383 

384 

385def _get_layer_checks(func: Callable, layers: tuple) -> tuple: 

386 """ 

387 Build the per-layer checks of a (possibly merged) @deprecated_args wrapper. 

388 """ 

389 return tuple( 

390 (*_get_warn_check(func, warned, allowed), warned, allowed, reason, version) 

391 for warned, allowed, reason, version in layers 

392 ) 

393 

394 

395def _merge_warn_checks( 

396 checks: tuple, 

397) -> tuple[int, Callable[[Any, frozenset], bool], frozenset]: 

398 """ 

399 Combine the per-layer pre-checks into one that passes exactly when every 

400 layer's would: below every layer's positional index, and kwargs disjoint 

401 from every named layer's names and within every wildcard layer's allowed 

402 names. 

403 """ 

404 if len(checks) == 1: 

405 return checks[0][:3] 

406 min_idx = min(check[0] for check in checks) 

407 named = frozenset().union( 

408 *(check[2] for check in checks if check[1] is _DictKeys.isdisjoint) 

409 ) 

410 wildcard = [check[2] for check in checks if check[1] is not _DictKeys.isdisjoint] 

411 if wildcard: 

412 return min_idx, _DictKeys.__le__, frozenset.intersection(*wildcard) - named 

413 return min_idx, _DictKeys.isdisjoint, named 

414 

415 

416def _check_deprecated_layers( 

417 func: Callable, checks: tuple, args: tuple, kwargs: dict 

418) -> None: 

419 """ 

420 Check and warn about deprecated arguments, one layer at a time. Every 

421 layer warns with stacklevel 4, the caller of the single wrapper frame. 

422 """ 

423 for min_idx, keys_ok, names, warned, allowed, reason, version in checks: 

424 if len(args) <= min_idx and (not kwargs or keys_ok(kwargs.keys(), names)): 

425 continue 

426 filterable_args = _get_filterable_args(func, args, kwargs, allowed) 

427 for arg in warned: 

428 if arg == "*" and len(filterable_args) > 0: 

429 warn_deprecated_arg_usage( 

430 list(filterable_args.keys()), 

431 func.__name__, 

432 reason, 

433 version, 

434 stacklevel=4, 

435 ) 

436 elif arg in filterable_args: 

437 warn_deprecated_arg_usage( 

438 arg, func.__name__, reason, version, stacklevel=4 

439 ) 

440 

441 

442def _set_info_logger(): 

443 """ 

444 Set up a logger that log info logs to stdout. 

445 (This is used by the default push response handler) 

446 """ 

447 if "push_response" not in logging.root.manager.loggerDict.keys(): 

448 logger = logging.getLogger("push_response") 

449 logger.setLevel(logging.INFO) 

450 handler = logging.StreamHandler() 

451 handler.setLevel(logging.INFO) 

452 logger.addHandler(handler) 

453 

454 

455#: Default RESP protocol version used on the wire when the user does not 

456#: supply an explicit ``protocol`` to the client / connection / pool. Lives 

457#: in ``redis.utils`` so both ``redis.connection`` (for the HELLO handshake) 

458#: and ``check_protocol_version`` (for protocol-gated features) can read it 

459#: without a circular import. 

460DEFAULT_RESP_VERSION = 3 

461 

462 

463def check_protocol_version( 

464 protocol: str | int | object | None, expected_version: int = 3 

465) -> bool: 

466 if protocol is None or protocol is SENTINEL: 

467 protocol = DEFAULT_RESP_VERSION 

468 if isinstance(protocol, str): 

469 try: 

470 protocol = int(protocol) 

471 except ValueError: 

472 return False 

473 return protocol == expected_version 

474 

475 

476@cache 

477def get_lib_version(): 

478 try: 

479 libver = metadata.version("redis") 

480 except metadata.PackageNotFoundError: 

481 libver = "99.99.99" 

482 return libver 

483 

484 

485def format_error_message(host_error: str, exception: BaseException) -> str: 

486 if not exception.args: 

487 return f"Error connecting to {host_error}." 

488 elif len(exception.args) == 1: 

489 return f"Error {exception.args[0]} connecting to {host_error}." 

490 else: 

491 return ( 

492 f"Error {exception.args[0]} connecting to {host_error}. " 

493 f"{exception.args[1]}." 

494 ) 

495 

496 

497def compare_versions(version1: str, version2: str) -> int: 

498 """ 

499 Compare two versions. 

500 

501 :return: -1 if version1 > version2 

502 0 if both versions are equal 

503 1 if version1 < version2 

504 """ 

505 

506 num_versions1 = list(map(int, version1.split("."))) 

507 num_versions2 = list(map(int, version2.split("."))) 

508 

509 if len(num_versions1) > len(num_versions2): 

510 diff = len(num_versions1) - len(num_versions2) 

511 for _ in range(diff): 

512 num_versions2.append(0) 

513 elif len(num_versions1) < len(num_versions2): 

514 diff = len(num_versions2) - len(num_versions1) 

515 for _ in range(diff): 

516 num_versions1.append(0) 

517 

518 for i, ver in enumerate(num_versions1): 

519 if num_versions1[i] > num_versions2[i]: 

520 return -1 

521 elif num_versions1[i] < num_versions2[i]: 

522 return 1 

523 

524 return 0 

525 

526 

527def ensure_string(key): 

528 if isinstance(key, bytes): 

529 return key.decode("utf-8") 

530 elif isinstance(key, str): 

531 return key 

532 else: 

533 raise TypeError("Key must be either a string or bytes") 

534 

535 

536_ZERO_TIMEDELTA = datetime.timedelta(0) 

537_ONE_MILLISECOND = datetime.timedelta(milliseconds=1) 

538 

539 

540def _timedelta_to_ms(td: datetime.timedelta) -> int: 

541 # Integer arithmetic: total_seconds() * 1000 goes through a float and can 

542 # come out 1 ms low (1.001 * 1000 == 1000.9999999999999). Truncates toward 

543 # zero, as int() did. 

544 if td < _ZERO_TIMEDELTA: 

545 return -(-td // _ONE_MILLISECOND) 

546 return td // _ONE_MILLISECOND 

547 

548 

549_UNIX_EPOCH = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc) 

550 

551 

552def _datetime_to_unix_ms(dt: datetime.datetime) -> int: 

553 if dt.utcoffset() is None: 

554 # Resolve local time at whole-second precision, then add the original 

555 # microseconds separately to avoid float rounding and UTC overflow. 

556 seconds = int(dt.replace(tzinfo=None, microsecond=0).timestamp()) 

557 return _timedelta_to_ms( 

558 datetime.timedelta(seconds=seconds, microseconds=dt.microsecond) 

559 ) 

560 

561 # Aware subtraction is exact even when conversion to UTC would overflow. 

562 return _timedelta_to_ms(dt - _UNIX_EPOCH) 

563 

564 

565def extract_expire_flags( 

566 ex: ExpiryT | str | None = None, 

567 px: ExpiryT | str | None = None, 

568 exat: Optional[AbsExpiryT] = None, 

569 pxat: Optional[AbsExpiryT] = None, 

570) -> List[EncodableT]: 

571 exp_options: list[EncodableT] = [] 

572 if ex is not None: 

573 exp_options.append("EX") 

574 if isinstance(ex, datetime.timedelta): 

575 exp_options.append(int(ex.total_seconds())) 

576 elif isinstance(ex, int): 

577 exp_options.append(ex) 

578 elif isinstance(ex, str) and ex.isdecimal(): 

579 exp_options.append(int(ex)) 

580 else: 

581 raise DataError("ex must be datetime.timedelta, int, or a digit string") 

582 elif px is not None: 

583 exp_options.append("PX") 

584 if isinstance(px, datetime.timedelta): 

585 exp_options.append(_timedelta_to_ms(px)) 

586 elif isinstance(px, int): 

587 exp_options.append(px) 

588 elif isinstance(px, str) and px.isdecimal(): 

589 exp_options.append(int(px)) 

590 else: 

591 raise DataError("px must be datetime.timedelta, int, or a digit string") 

592 elif exat is not None: 

593 if isinstance(exat, datetime.datetime): 

594 exat = int(exat.timestamp()) 

595 exp_options.extend(["EXAT", exat]) 

596 elif pxat is not None: 

597 if isinstance(pxat, datetime.datetime): 

598 pxat = _datetime_to_unix_ms(pxat) 

599 exp_options.extend(["PXAT", pxat]) 

600 

601 return exp_options 

602 

603 

604def truncate_text(txt, max_length=100): 

605 return textwrap.shorten( 

606 text=txt, width=max_length, placeholder="...", break_long_words=True 

607 ) 

608 

609 

610# Commands whose arguments can carry credentials. 

611_CREDENTIAL_COMMANDS = frozenset( 

612 {"AUTH", "HELLO", "MIGRATE", "ACL SETUSER", "CONFIG SET", "SENTINEL SET"} 

613) 

614 

615 

616def command_text(command): 

617 """ 

618 Render a command for an error message, replacing the arguments of commands 

619 that can carry credentials (AUTH, HELLO, MIGRATE, ACL SETUSER, CONFIG SET, 

620 SENTINEL SET) with a placeholder, so passwords do not end up in exceptions 

621 and logs. 

622 """ 

623 parts = [safe_str(arg) for arg in command] 

624 name_len = 0 

625 if parts: 

626 name = parts[0].upper() 

627 if name in _CREDENTIAL_COMMANDS: 

628 name_len = 1 

629 elif len(parts) > 1 and f"{name} {parts[1].upper()}" in _CREDENTIAL_COMMANDS: 

630 name_len = 2 

631 if name_len and len(parts) > name_len: 

632 parts[name_len:] = ["<REDACTED>"] 

633 return " ".join(parts) 

634 

635 

636def dummy_fail(): 

637 """ 

638 Fake function for a Retry object if you don't need to handle each failure. 

639 """ 

640 pass 

641 

642 

643async def dummy_fail_async(): 

644 """ 

645 Async fake function for a Retry object if you don't need to handle each failure. 

646 """ 

647 pass 

648 

649 

650def experimental(cls): 

651 """ 

652 Decorator to mark a class as experimental. 

653 """ 

654 original_init = cls.__init__ 

655 

656 @wraps(original_init) 

657 def new_init(self, *args, **kwargs): 

658 warnings.warn( 

659 f"{cls.__name__} is an experimental and may change or be removed in future versions.", 

660 category=UserWarning, 

661 stacklevel=2, 

662 ) 

663 original_init(self, *args, **kwargs) 

664 

665 cls.__init__ = new_init 

666 return cls 

667 

668 

669def warn_experimental(name, stacklevel=2): 

670 import warnings 

671 

672 msg = ( 

673 f"Call to experimental method {name}. " 

674 "Be aware that the function arguments can " 

675 "change or be removed in future versions." 

676 ) 

677 warnings.warn(msg, category=UserWarning, stacklevel=stacklevel) 

678 

679 

680def experimental_method() -> Callable[[C], C]: 

681 """ 

682 Decorator to mark a function as experimental. 

683 """ 

684 

685 def decorator(func: C) -> C: 

686 if inspect.iscoroutinefunction(func): 

687 # Create async wrapper for async functions 

688 @wraps(func) 

689 async def async_wrapper(*args, **kwargs): 

690 warn_experimental(func.__name__, stacklevel=2) 

691 return await func(*args, **kwargs) 

692 

693 return async_wrapper 

694 else: 

695 # Create regular wrapper for sync functions 

696 @wraps(func) 

697 def wrapper(*args, **kwargs): 

698 warn_experimental(func.__name__, stacklevel=2) 

699 return func(*args, **kwargs) 

700 

701 return wrapper 

702 

703 return decorator 

704 

705 

706def warn_experimental_arg_usage( 

707 arg_name: Union[list, str], 

708 function_name: str, 

709 stacklevel: int = 2, 

710): 

711 import warnings 

712 

713 msg = ( 

714 f"Call to '{function_name}' method with experimental" 

715 f" usage of input argument/s '{arg_name}'." 

716 ) 

717 warnings.warn(msg, category=UserWarning, stacklevel=stacklevel) 

718 

719 

720def experimental_args( 

721 args_to_warn: Optional[List[str]] = None, 

722) -> Callable[[C], C]: 

723 """ 

724 Decorator to mark specified args of a function as experimental. 

725 If '*' is in args_to_warn, all arguments will be marked as experimental. 

726 """ 

727 warned = tuple(args_to_warn) if args_to_warn is not None else ("*",) 

728 

729 def _check_experimental_args(func, filterable_args): 

730 """Check and warn about experimental arguments.""" 

731 for arg in warned: 

732 if arg == "*" and len(filterable_args) > 0: 

733 warn_experimental_arg_usage( 

734 list(filterable_args.keys()), func.__name__, stacklevel=4 

735 ) 

736 elif arg in filterable_args: 

737 warn_experimental_arg_usage(arg, func.__name__, stacklevel=4) 

738 

739 def decorator(func: C) -> C: 

740 min_idx, keys_ok, names = _get_warn_check(func, warned) 

741 

742 if inspect.iscoroutinefunction(func): 

743 

744 @wraps(func) 

745 async def async_wrapper(*args, **kwargs): 

746 if len(args) > min_idx or ( 

747 kwargs and not keys_ok(kwargs.keys(), names) 

748 ): 

749 filterable_args = _get_filterable_args(func, args, kwargs) 

750 if len(filterable_args) > 0: 

751 _check_experimental_args(func, filterable_args) 

752 return await func(*args, **kwargs) 

753 

754 return async_wrapper 

755 else: 

756 

757 @wraps(func) 

758 def wrapper(*args, **kwargs): 

759 if len(args) > min_idx or ( 

760 kwargs and not keys_ok(kwargs.keys(), names) 

761 ): 

762 filterable_args = _get_filterable_args(func, args, kwargs) 

763 if len(filterable_args) > 0: 

764 _check_experimental_args(func, filterable_args) 

765 return func(*args, **kwargs) 

766 

767 return wrapper 

768 

769 return decorator