|
| 1 | +from functools import wraps |
| 2 | + |
| 3 | +from packaging.version import Version |
| 4 | + |
| 5 | +from .exceptions import VersionUpgradeRequiredException |
| 6 | + |
| 7 | + |
| 8 | +def requires_version(expected: str): |
| 9 | + """ |
| 10 | + Decorator to enforce a minimum version requirement for a method. |
| 11 | +
|
| 12 | + This decorator checks the `version` attribute of the class instance and raises a `VersionUpgradeRequiredException` if the version is lower than the specified `expected` version. |
| 13 | +
|
| 14 | + Parameters |
| 15 | + ---------- |
| 16 | + expected : str |
| 17 | + The minimum version required for the decorated method to execute. It is compared against the class instance's `version` attribute. |
| 18 | +
|
| 19 | + Returns |
| 20 | + ------- |
| 21 | + function |
| 22 | + The wrapped function that enforces the version check. |
| 23 | +
|
| 24 | + Raises |
| 25 | + ------ |
| 26 | + VersionUpgradeRequiredException |
| 27 | + If the version specified in the class instance's `version` attribute is lower than the `expected` version. |
| 28 | +
|
| 29 | + Examples |
| 30 | + -------- |
| 31 | + To use this decorator, apply it to any method that requires a minimum version: |
| 32 | +
|
| 33 | + >>> class Client: |
| 34 | + >>> version = "2024.07.0" |
| 35 | + >>> |
| 36 | + >>> @requires_version("2024.08.0") |
| 37 | + >>> def some_method(self): |
| 38 | + >>> pass |
| 39 | + >>> |
| 40 | + >>> client = Client() |
| 41 | + >>> client.some_method() |
| 42 | + Traceback (most recent call last): |
| 43 | + ... |
| 44 | + VersionUpgradeRequiredException: This API is not available in Connect version 2024.07.0. Please upgrade to version 2024.08.0 or later." |
| 45 | +
|
| 46 | + """ |
| 47 | + |
| 48 | + def decorator(func): |
| 49 | + @wraps(func) |
| 50 | + def wrapper(self, *args, **kwargs): |
| 51 | + if hasattr(self, "version"): |
| 52 | + version = getattr(self, "version") |
| 53 | + if not version: |
| 54 | + return |
| 55 | + if Version(version) < Version(expected): |
| 56 | + raise VersionUpgradeRequiredException(version, expected) |
| 57 | + return func(self, *args, **kwargs) |
| 58 | + |
| 59 | + return wrapper |
| 60 | + |
| 61 | + return decorator |
0 commit comments