dwave-cloud-client 0.13.0__tar.gz → 0.13.2__tar.gz

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 (75) hide show
  1. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/PKG-INFO +31 -6
  2. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/api/client.py +16 -19
  3. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/api/constants.py +5 -9
  4. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/api/models.py +5 -6
  5. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/api/resources.py +20 -19
  6. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/auth/creds.py +4 -2
  7. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/auth/flows.py +7 -6
  8. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/auth/server.py +9 -6
  9. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/cli.py +40 -16
  10. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/client/base.py +10 -9
  11. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/coders.py +22 -46
  12. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/computation.py +12 -7
  13. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/config/__init__.py +2 -0
  14. dwave_cloud_client-0.13.2/dwave/cloud/config/constants.py +33 -0
  15. dwave_cloud_client-0.13.2/dwave/cloud/config/exceptions.py +32 -0
  16. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/config/loaders.py +13 -11
  17. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/config/models.py +15 -14
  18. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/events.py +1 -1
  19. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/exceptions.py +6 -13
  20. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/package_info.py +1 -1
  21. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/regions.py +4 -4
  22. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/solver.py +50 -73
  23. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/testing/mocks.py +4 -4
  24. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/upload.py +2 -2
  25. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/utils/cli.py +4 -3
  26. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/utils/decorators.py +7 -6
  27. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/utils/dist.py +4 -4
  28. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/utils/exception.py +4 -3
  29. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/utils/http.py +4 -4
  30. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/utils/logging.py +12 -12
  31. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/utils/qubo.py +9 -8
  32. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave_cloud_client.egg-info/PKG-INFO +31 -6
  33. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave_cloud_client.egg-info/SOURCES.txt +19 -1
  34. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave_cloud_client.egg-info/requires.txt +1 -9
  35. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/setup.py +3 -5
  36. dwave_cloud_client-0.13.2/tests/test_cli.py +767 -0
  37. dwave_cloud_client-0.13.2/tests/test_client.py +1260 -0
  38. dwave_cloud_client-0.13.2/tests/test_coders.py +335 -0
  39. dwave_cloud_client-0.13.2/tests/test_concurrency.py +154 -0
  40. dwave_cloud_client-0.13.2/tests/test_config.py +706 -0
  41. dwave_cloud_client-0.13.2/tests/test_events.py +234 -0
  42. dwave_cloud_client-0.13.2/tests/test_exceptions.py +32 -0
  43. dwave_cloud_client-0.13.2/tests/test_mock_solver_loading.py +356 -0
  44. dwave_cloud_client-0.13.2/tests/test_mock_submission.py +1236 -0
  45. dwave_cloud_client-0.13.2/tests/test_mock_unstructured_submission.py +637 -0
  46. dwave_cloud_client-0.13.2/tests/test_regions.py +172 -0
  47. dwave_cloud_client-0.13.2/tests/test_solver.py +670 -0
  48. dwave_cloud_client-0.13.2/tests/test_solver_utils.py +188 -0
  49. dwave_cloud_client-0.13.2/tests/test_testing.py +282 -0
  50. dwave_cloud_client-0.13.2/tests/test_upload.py +800 -0
  51. dwave_cloud_client-0.13.2/tests/test_utils.py +1152 -0
  52. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/LICENSE +0 -0
  53. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/README.rst +0 -0
  54. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/__init__.py +0 -0
  55. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/__init__.py +0 -0
  56. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/api/__init__.py +0 -0
  57. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/api/exceptions.py +0 -0
  58. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/auth/__init__.py +0 -0
  59. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/auth/_creds.py +0 -0
  60. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/auth/config.py +0 -0
  61. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/client/__init__.py +0 -0
  62. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/client/hybrid.py +0 -0
  63. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/client/qpu.py +0 -0
  64. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/client/sw.py +0 -0
  65. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/concurrency.py +0 -0
  66. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/testing/__init__.py +0 -0
  67. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/utils/__init__.py +0 -0
  68. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/utils/coders.py +0 -0
  69. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave/cloud/utils/time.py +0 -0
  70. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave_cloud_client.egg-info/dependency_links.txt +0 -0
  71. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave_cloud_client.egg-info/entry_points.txt +0 -0
  72. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave_cloud_client.egg-info/not-zip-safe +0 -0
  73. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/dwave_cloud_client.egg-info/top_level.txt +0 -0
  74. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/pyproject.toml +0 -0
  75. {dwave-cloud-client-0.13.0 → dwave_cloud_client-0.13.2}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: dwave-cloud-client
3
- Version: 0.13.0
3
+ Version: 0.13.2
4
4
  Summary: A minimal client for interacting with D-Wave cloud resources.
5
5
  Home-page: https://github.com/dwavesystems/dwave-cloud-client
6
6
  Author: D-Wave Systems Inc.
@@ -8,21 +8,46 @@ License: Apache 2.0
8
8
  Classifier: License :: OSI Approved :: Apache Software License
9
9
  Classifier: Operating System :: OS Independent
10
10
  Classifier: Programming Language :: Python :: 3
11
- Classifier: Programming Language :: Python :: 3.8
12
11
  Classifier: Programming Language :: Python :: 3.9
13
12
  Classifier: Programming Language :: Python :: 3.10
14
13
  Classifier: Programming Language :: Python :: 3.11
15
14
  Classifier: Programming Language :: Python :: 3.12
16
- Requires-Python: >=3.8
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Requires-Python: >=3.9
17
+ License-File: LICENSE
18
+ Requires-Dist: requests[socks]<3,>=2.25
19
+ Requires-Dist: urllib3<3,>=1.26
20
+ Requires-Dist: pydantic<3,>=2
21
+ Requires-Dist: homebase<2,>=1.0
22
+ Requires-Dist: click<9,>=7.0
23
+ Requires-Dist: python-dateutil<3,>=2.7
24
+ Requires-Dist: plucky<0.5,>=0.4.3
25
+ Requires-Dist: diskcache<6,>=5.2.1
26
+ Requires-Dist: packaging>=19
27
+ Requires-Dist: werkzeug<4,>=2.2
28
+ Requires-Dist: typing-extensions<5,>=4.5.0
29
+ Requires-Dist: authlib<2,>=1.2
30
+ Requires-Dist: importlib_metadata>=5.0.0
31
+ Requires-Dist: orjson>=3.10
17
32
  Provides-Extra: test
33
+ Requires-Dist: requests_mock; extra == "test"
34
+ Requires-Dist: mock; extra == "test"
35
+ Requires-Dist: numpy; extra == "test"
36
+ Requires-Dist: coverage; extra == "test"
18
37
  Provides-Extra: bqm
19
- Provides-Extra: bqm-legacy
38
+ Requires-Dist: dimod!=0.11.4,<0.13,>=0.10.5; extra == "bqm"
39
+ Requires-Dist: numpy>=1.17.3; extra == "bqm"
20
40
  Provides-Extra: dqm
21
- Provides-Extra: dqm-legacy
41
+ Requires-Dist: dimod!=0.11.4,<0.13,>=0.10.5; extra == "dqm"
42
+ Requires-Dist: numpy>=1.17.3; extra == "dqm"
22
43
  Provides-Extra: cqm
44
+ Requires-Dist: dimod!=0.11.4,<0.13,>=0.10.5; extra == "cqm"
45
+ Requires-Dist: numpy>=1.17.3; extra == "cqm"
23
46
  Provides-Extra: nlm
47
+ Requires-Dist: dwave-optimization<0.5,>=0.1.0; extra == "nlm"
48
+ Requires-Dist: numpy>=1.20.0; extra == "nlm"
24
49
  Provides-Extra: mocks
25
- License-File: LICENSE
50
+ Requires-Dist: dwave-networkx>=0.8.10; extra == "mocks"
26
51
 
27
52
  .. image:: https://badge.fury.io/py/dwave-cloud-client.svg
28
53
  :target: https://badge.fury.io/py/dwave-cloud-client
@@ -20,8 +20,8 @@ import logging
20
20
  import numbers
21
21
  import os
22
22
  import warnings
23
- from collections import deque, namedtuple
24
- from typing import Callable, Mapping, Optional, Tuple, TypedDict, Union, TYPE_CHECKING
23
+ from collections import deque, namedtuple, abc
24
+ from typing import Optional, TypedDict, Union, TYPE_CHECKING
25
25
 
26
26
  import orjson
27
27
  import requests
@@ -29,8 +29,8 @@ import urllib3
29
29
  import werkzeug
30
30
  from packaging.specifiers import SpecifierSet
31
31
 
32
- import dwave.cloud.config # don't use `from` to break circular import (config <> api.constants)
33
- from dwave.cloud.api import constants, exceptions
32
+ import dwave.cloud.config
33
+ from dwave.cloud.api import exceptions
34
34
  from dwave.cloud.utils.exception import is_caused_by
35
35
  from dwave.cloud.utils.http import PretimedHTTPAdapter, BaseUrlSession, default_user_agent
36
36
  from dwave.cloud.utils.time import epochnow
@@ -235,7 +235,7 @@ class VersionedAPISession(LoggingSession):
235
235
  return response
236
236
 
237
237
 
238
- def _create_default_cache_store(**kwargs) -> Mapping:
238
+ def _create_default_cache_store(**kwargs) -> abc.Mapping:
239
239
  # TODO: de-dup vs `dwave.cloud.utils.decorators.cached`?
240
240
 
241
241
  # defer to break circular imports
@@ -282,14 +282,10 @@ class CachingSession(VersionedAPISession):
282
282
  Force cache update, skipping time-based or etag-based validation.
283
283
  """
284
284
 
285
- _cache_enabled = False
286
- _maxage = None
287
- _store = None
288
-
289
285
  class CacheConfig(TypedDict, total=False):
290
286
  enabled: bool
291
287
  maxage: float
292
- store: Union[Mapping, Callable[[], Mapping]]
288
+ store: Union[abc.Mapping, abc.Callable[[], abc.Mapping]]
293
289
 
294
290
  # default cache config
295
291
  _default_cache_config = CacheConfig(enabled=True,
@@ -336,7 +332,7 @@ class CachingSession(VersionedAPISession):
336
332
  def _parse_cache_control(
337
333
  self,
338
334
  cache_control: Optional[str] = None,
339
- ) -> Tuple[bool, Optional[int]]:
335
+ ) -> tuple[bool, Optional[int]]:
340
336
  # parse Cache-Control header field (if present) and derive a suitable max-age value
341
337
  # returns: (cache?, maxage)
342
338
 
@@ -404,6 +400,11 @@ class CachingSession(VersionedAPISession):
404
400
  refresh = kwargs.pop('refresh_', False)
405
401
  no_cache = kwargs.pop('no_cache_', False)
406
402
  default_maxage = kwargs.pop('maxage_', None)
403
+
404
+ if not self._cache_enabled or no_cache or method.lower() != 'get':
405
+ # completely bypass cache lookup and validation
406
+ return super().request(method, url, params=params, headers=headers, **kwargs)
407
+
407
408
  if default_maxage is None:
408
409
  default_maxage = self._maxage
409
410
  elif not isinstance(default_maxage, numbers.Real) or default_maxage < 0:
@@ -412,10 +413,6 @@ class CachingSession(VersionedAPISession):
412
413
  UserWarning, stacklevel=2)
413
414
  default_maxage = self._maxage
414
415
 
415
- if not self._cache_enabled or no_cache or method.lower() != 'get':
416
- # completely bypass cache lookup and validation
417
- return super().request(method, url, params=params, headers=headers, **kwargs)
418
-
419
416
  key = (method,
420
417
  self.base_url, url,
421
418
  self.params, params,
@@ -580,7 +577,7 @@ class DWaveAPIClient:
580
577
  return cls.from_config_model(config)
581
578
 
582
579
  @classmethod
583
- def from_config(cls, config: Optional[Union[ClientConfig, str]] = None, **kwargs):
580
+ def from_config(cls, config: Union[ClientConfig, str, None] = None, **kwargs):
584
581
  """Create class instance based on client config or config file.
585
582
 
586
583
  Args:
@@ -729,7 +726,7 @@ class SolverAPIClient(DWaveAPIClient):
729
726
  def __init__(self, **config):
730
727
  # TODO: make endpoint region-sensitive
731
728
  self.DEFAULTS = super().DEFAULTS.copy()
732
- self.DEFAULTS.update(endpoint=constants.DEFAULT_SOLVER_API_ENDPOINT)
729
+ self.DEFAULTS.update(endpoint=dwave.cloud.config.constants.DEFAULT_SOLVER_API_ENDPOINT)
733
730
 
734
731
  super().__init__(**config)
735
732
 
@@ -740,7 +737,7 @@ class MetadataAPIClient(DWaveAPIClient):
740
737
  def __init__(self, **config):
741
738
  # TODO: make endpoint region-sensitive
742
739
  self.DEFAULTS = super().DEFAULTS.copy()
743
- self.DEFAULTS.update(endpoint=constants.DEFAULT_METADATA_API_ENDPOINT)
740
+ self.DEFAULTS.update(endpoint=dwave.cloud.config.constants.DEFAULT_METADATA_API_ENDPOINT)
744
741
 
745
742
  super().__init__(**config)
746
743
 
@@ -761,7 +758,7 @@ class LeapAPIClient(DWaveAPIClient):
761
758
  def __init__(self, **config):
762
759
  # TODO: make endpoint region-sensitive
763
760
  self.DEFAULTS = super().DEFAULTS.copy()
764
- self.DEFAULTS.update(endpoint=constants.DEFAULT_LEAP_API_ENDPOINT)
761
+ self.DEFAULTS.update(endpoint=dwave.cloud.config.constants.DEFAULT_LEAP_API_ENDPOINT)
765
762
 
766
763
  super().__init__(**config)
767
764
 
@@ -14,15 +14,11 @@
14
14
 
15
15
  import enum
16
16
 
17
-
18
- # Default API endpoints
19
- DEFAULT_SOLVER_API_ENDPOINT = 'https://cloud.dwavesys.com/sapi/'
20
-
21
- DEFAULT_METADATA_API_ENDPOINT = 'https://cloud.dwavesys.com/metadata/v1/'
22
-
23
- DEFAULT_LEAP_API_ENDPOINT = 'https://cloud.dwavesys.com/leap/api/'
24
-
25
- DEFAULT_REGION = 'na-west-1'
17
+ # note: for backwards compatibility in 0.13.1+
18
+ # TODO: remove in 0.14.0
19
+ from dwave.cloud.config.constants import (
20
+ DEFAULT_METADATA_API_ENDPOINT, DEFAULT_REGION,
21
+ DEFAULT_SOLVER_API_ENDPOINT, DEFAULT_LEAP_API_ENDPOINT)
26
22
 
27
23
 
28
24
  # Default API version
@@ -13,8 +13,7 @@
13
13
  # limitations under the License.
14
14
 
15
15
  from datetime import datetime
16
- from typing import List, Union, Optional, Dict, Any
17
- from typing_extensions import Annotated # backport for py37, py38
16
+ from typing import Annotated, Any, Optional, Union
18
17
 
19
18
  from pydantic import BaseModel, RootModel, ConfigDict
20
19
  from pydantic.functional_validators import AfterValidator
@@ -147,20 +146,20 @@ class ProblemMetadata(BaseModel):
147
146
  submitted_by: str
148
147
  submitted_on: datetime
149
148
  solved_on: Optional[datetime] = None
150
- messages: Optional[List[dict]] = None
149
+ messages: Optional[list[dict]] = None
151
150
 
152
151
 
153
152
  class ProblemInfo(BaseModel):
154
153
  id: str
155
154
  data: ProblemData
156
- params: Dict[str, AnyIncludingNumpy]
155
+ params: dict[str, AnyIncludingNumpy]
157
156
  metadata: ProblemMetadata
158
157
  answer: ProblemAnswer
159
158
 
160
159
 
161
160
  class ProblemJob(BaseModel):
162
161
  data: ProblemData
163
- params: Dict[str, AnyIncludingNumpy]
162
+ params: dict[str, AnyIncludingNumpy]
164
163
  solver: str
165
164
  type: constants.ProblemType
166
165
  label: Optional[str] = None
@@ -210,7 +209,7 @@ class _LeapActiveProjectResponse(BaseModel):
210
209
 
211
210
  # LeapAPI / account / projects response
212
211
  class _LeapProjectsWrapper(BaseModel):
213
- projects: List[_LeapProjectWrapper]
212
+ projects: list[_LeapProjectWrapper]
214
213
 
215
214
  class _LeapProjectsResponse(BaseModel):
216
215
  data: _LeapProjectsWrapper
@@ -16,14 +16,15 @@ from __future__ import annotations
16
16
 
17
17
  import io
18
18
  import orjson
19
- from typing import List, Union, Optional, Callable, get_type_hints, TYPE_CHECKING
19
+ from collections import abc
20
+ from typing import Union, Optional, get_type_hints, TYPE_CHECKING
20
21
  from functools import wraps
21
22
 
22
23
  from pydantic import TypeAdapter
23
24
 
25
+ from dwave.cloud.api import constants, models
24
26
  from dwave.cloud.api.client import (
25
27
  DWaveAPIClient, SolverAPIClient, MetadataAPIClient, LeapAPIClient)
26
- from dwave.cloud.api import constants, models
27
28
 
28
29
  if TYPE_CHECKING:
29
30
  from dwave.cloud.config.models import ClientConfig
@@ -44,7 +45,7 @@ class accepts:
44
45
  self.ctx = dict(media_type=media_type, accept_version=version)
45
46
  self.ctx.update(kwargs)
46
47
 
47
- def __call__(self, fn: Callable):
48
+ def __call__(self, fn: abc.Callable):
48
49
  @wraps(fn)
49
50
  def wrapper(obj: 'ResourceBase', *args, **kwargs):
50
51
  try:
@@ -105,11 +106,11 @@ class Regions(ResourceBase):
105
106
  client_class = MetadataAPIClient
106
107
 
107
108
  @accepts(media_type='application/vnd.dwave.metadata.regions+json', version='~=1.0')
108
- def list_regions(self, **kwargs) -> List[models.Region]:
109
+ def list_regions(self, **kwargs) -> list[models.Region]:
109
110
  path = ''
110
111
  response = self.session.get(path, **kwargs)
111
112
  regions = orjson.loads(response.content)
112
- return TypeAdapter(List[models.Region]).validate_python(regions)
113
+ return TypeAdapter(list[models.Region]).validate_python(regions)
113
114
 
114
115
  @accepts(media_type='application/vnd.dwave.metadata.region+json', version='~=1.0')
115
116
  def get_region(self, code: str, **kwargs) -> models.Region:
@@ -125,7 +126,7 @@ class Solvers(ResourceBase):
125
126
  client_class = SolverAPIClient
126
127
 
127
128
  @accepts(media_type='application/vnd.dwave.sapi.solver-definition-list+json', version='~=2.0')
128
- def list_solvers(self, filter: Optional[str] = None, **kwargs) -> List[models.SolverConfiguration]:
129
+ def list_solvers(self, filter: Optional[str] = None, **kwargs) -> list[models.SolverConfiguration]:
129
130
  path = 'remote/'
130
131
  params = {'filter': filter} if filter is not None else None
131
132
  response = self.session.get(path, params=params, **kwargs)
@@ -133,7 +134,7 @@ class Solvers(ResourceBase):
133
134
  # tl;dr: model_validate() on orjson-decoded content is much faster then
134
135
  # model_validate_json() and faster than model_validate on json-decoded
135
136
  solvers = orjson.loads(response.content)
136
- return TypeAdapter(List[models.SolverConfiguration]).validate_python(solvers)
137
+ return TypeAdapter(list[models.SolverConfiguration]).validate_python(solvers)
137
138
 
138
139
  @accepts(media_type='application/vnd.dwave.sapi.solver-definition+json', version='~=2.0')
139
140
  def get_solver(self, solver_id: str, filter: Optional[str] = None, **kwargs) -> models.SolverConfiguration:
@@ -156,7 +157,7 @@ class Problems(ResourceBase):
156
157
  max_results: int = None,
157
158
  status: Union[str, constants.ProblemStatus] = None,
158
159
  solver: str = None,
159
- **params) -> List[models.ProblemStatus]:
160
+ **params) -> list[models.ProblemStatus]:
160
161
  """Retrieve a filtered list of submitted problems."""
161
162
 
162
163
  # build query
@@ -176,7 +177,7 @@ class Problems(ResourceBase):
176
177
  path = ''
177
178
  response = self.session.get(path, params=params)
178
179
  statuses = orjson.loads(response.content)
179
- return TypeAdapter(List[models.ProblemStatus]).validate_python(statuses)
180
+ return TypeAdapter(list[models.ProblemStatus]).validate_python(statuses)
180
181
 
181
182
  @accepts(media_type='application/vnd.dwave.sapi.problem+json', version='>=2.1,<3')
182
183
  def get_problem(self,
@@ -209,9 +210,9 @@ class Problems(ResourceBase):
209
210
  # XXX: @pydantic.validate_arguments
210
211
  @accepts(media_type='application/vnd.dwave.sapi.problems+json', version='>=2.1,<3')
211
212
  def get_problem_statuses(self,
212
- problem_ids: List[str],
213
+ problem_ids: list[str],
213
214
  timeout: Optional[int] = None,
214
- ) -> List[models.ProblemStatus]:
215
+ ) -> list[models.ProblemStatus]:
215
216
  """Retrieve short problem statuses for a list of problems."""
216
217
  if not isinstance(problem_ids, list):
217
218
  raise TypeError('a list of problem ids expected')
@@ -224,7 +225,7 @@ class Problems(ResourceBase):
224
225
  params.setdefault('timeout', timeout)
225
226
  response = self.session.get(path, params=params)
226
227
  statuses = orjson.loads(response.content)
227
- return TypeAdapter(List[models.ProblemStatus]).validate_python(statuses)
228
+ return TypeAdapter(list[models.ProblemStatus]).validate_python(statuses)
228
229
 
229
230
  @accepts(media_type='application/vnd.dwave.sapi.problem-data+json', version='>=2.1,<3')
230
231
  def get_problem_info(self, problem_id: str) -> models.ProblemInfo:
@@ -260,7 +261,7 @@ class Problems(ResourceBase):
260
261
  return output
261
262
 
262
263
  @accepts(media_type='application/vnd.dwave.sapi.problem-message+json', version='>=2.1,<3')
263
- def get_problem_messages(self, problem_id: str) -> List[dict]:
264
+ def get_problem_messages(self, problem_id: str) -> list[dict]:
264
265
  """Retrieve list of problem messages."""
265
266
  path = '{}/messages'.format(problem_id)
266
267
  response = self.session.get(path)
@@ -272,7 +273,7 @@ class Problems(ResourceBase):
272
273
  params: dict,
273
274
  solver: str,
274
275
  type: constants.ProblemType,
275
- label: str = None) -> \
276
+ label: Optional[str] = None) -> \
276
277
  Union[models.ProblemStatusMaybeWithAnswer, models.ProblemSubmitError]:
277
278
  """Blocking problem submit with timeout, returning final status and
278
279
  answer, if problem is solved within the (undisclosed) time limit.
@@ -289,8 +290,8 @@ class Problems(ResourceBase):
289
290
  return TypeAdapter(rtype).validate_python(orjson.loads(response.content))
290
291
 
291
292
  @accepts(media_type='application/vnd.dwave.sapi.problems+json', version='>=2.1,<3')
292
- def submit_problems(self, problems: List[models.ProblemJob]) -> \
293
- List[Union[models.ProblemInitialStatus, models.ProblemSubmitError]]:
293
+ def submit_problems(self, problems: list[models.ProblemJob]) -> \
294
+ list[Union[models.ProblemInitialStatus, models.ProblemSubmitError]]:
294
295
  """Asynchronous multi-problem submit, returning initial statuses."""
295
296
  path = ''
296
297
  # note: TypeAdapter().dump_json() is 2ms vs 50us by orjson.dumps(model.model_dump())
@@ -310,8 +311,8 @@ class Problems(ResourceBase):
310
311
  return TypeAdapter(rtype).validate_python(orjson.loads(response.content))
311
312
 
312
313
  @accepts(media_type='application/vnd.dwave.sapi.problems+json', version='>=2.1,<3')
313
- def cancel_problems(self, problem_ids: List[str]) -> \
314
- List[Union[models.ProblemStatus, models.ProblemCancelError]]:
314
+ def cancel_problems(self, problem_ids: list[str]) -> \
315
+ list[Union[models.ProblemStatus, models.ProblemCancelError]]:
315
316
  """Initiate problem cancel for a list of problems."""
316
317
  path = ''
317
318
  response = self.session.delete(path, json=problem_ids)
@@ -334,7 +335,7 @@ class LeapAccount(ResourceBase):
334
335
  orjson.loads(response.content))
335
336
  return parsed.data.project
336
337
 
337
- def list_projects(self) -> List[models.LeapProject]:
338
+ def list_projects(self) -> list[models.LeapProject]:
338
339
  """Retrieve list of Leap projects accessible to the authenticated user."""
339
340
  path = 'projects/oauth/'
340
341
  response = self.session.get(path)
@@ -12,9 +12,11 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
+ from __future__ import annotations
16
+
15
17
  import logging
16
18
  from pathlib import Path
17
- from typing import List, Optional, Type, Union
19
+ from typing import Optional, Type, Union
18
20
 
19
21
  from dwave.cloud.auth._creds import _Cache
20
22
  from dwave.cloud.config import get_configfile_paths, get_default_configfile_path
@@ -31,7 +33,7 @@ class AutoDetect:
31
33
 
32
34
  def _get_creds_paths(
33
35
  *, system: bool = True, user: bool = True, local: bool = True,
34
- only_existing: bool = True) -> List[str]:
36
+ only_existing: bool = True) -> list[str]:
35
37
  return get_configfile_paths(system=system, user=user, local=local,
36
38
  only_existing=only_existing, filename=CREDS_FILENAME)
37
39
 
@@ -17,8 +17,9 @@ from __future__ import annotations
17
17
  import logging
18
18
  import time
19
19
  import webbrowser
20
+ from collections import abc
20
21
  from operator import sub
21
- from typing import Any, Callable, Dict, Optional, Union, Sequence, Literal, TYPE_CHECKING
22
+ from typing import Any, Optional, Union, Literal, TYPE_CHECKING
22
23
  from urllib.parse import urljoin
23
24
 
24
25
  import click
@@ -80,12 +81,12 @@ class AuthFlow:
80
81
 
81
82
  def __init__(self, *,
82
83
  client_id: str,
83
- scopes: Sequence[str],
84
+ scopes: abc.Sequence[str],
84
85
  redirect_uri: str,
85
86
  authorization_endpoint: str,
86
87
  token_endpoint: str,
87
88
  revocation_endpoint: Optional[str] = None,
88
- session_config: Optional[Dict[str, Any]] = None,
89
+ session_config: Optional[abc.Mapping[str, Any]] = None,
89
90
  leap_api_endpoint: Optional[str] = None,
90
91
  creds: Optional[Credentials] = None
91
92
  ):
@@ -130,7 +131,7 @@ class AuthFlow:
130
131
 
131
132
  logger.debug(f"{type(self).__name__} initialized with: {pretty_argvalues()}")
132
133
 
133
- def update_session(self, config: Dict[str, Any]) -> None:
134
+ def update_session(self, config: abc.Mapping[str, Any]) -> None:
134
135
  """Update OAuth2Session/requests.Session with config values for:
135
136
  ``cert``, ``cookies``, ``headers``, ``proxies``, ``timeout``, ``verify``.
136
137
  """
@@ -378,7 +379,7 @@ class LeapAuthFlow(AuthFlow):
378
379
 
379
380
  return flow
380
381
 
381
- def run_oob_flow(self, *, open_browser: Union[bool,Callable] = False):
382
+ def run_oob_flow(self, *, open_browser: Union[bool, abc.Callable] = False):
382
383
  """Run OAuth 2.0 code exchange (out-of-band flow.)
383
384
 
384
385
  Runs the OAuth 2.0 Authorization Code exchange flow using the out-of-band code
@@ -405,7 +406,7 @@ class LeapAuthFlow(AuthFlow):
405
406
  click.echo()
406
407
  return self.fetch_token(code=code)
407
408
 
408
- def run_redirect_flow(self, *, open_browser: Union[bool,Callable] = False,
409
+ def run_redirect_flow(self, *, open_browser: Union[bool, abc.Callable] = False,
409
410
  timeout: Optional[float] = None):
410
411
  """Run the OAuth 2.0 code exchange (using locally hosted redirect URI).
411
412
 
@@ -12,13 +12,16 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
+ from __future__ import annotations
16
+
15
17
  import logging
16
18
  import random
17
19
  import sys
18
20
  import threading
19
21
  import traceback
22
+ from collections import abc
20
23
  from socketserver import ThreadingMixIn
21
- from typing import Callable, Iterator, Optional, Union
24
+ from typing import Optional, Union
22
25
  from urllib.parse import urljoin, urlsplit, parse_qsl, SplitResult
23
26
  from wsgiref.simple_server import make_server, WSGIRequestHandler, WSGIServer
24
27
  from wsgiref.util import request_uri
@@ -102,7 +105,7 @@ class ThreadingWSGIServer(ThreadingMixIn, SocketTimeoutTCPServerMixin,
102
105
 
103
106
 
104
107
  def iterports(start: int, end: int,
105
- n_lin: int, n_rand: Optional[int] = None) -> Iterator[int]:
108
+ n_lin: int, n_rand: Optional[int] = None) -> abc.Iterator[int]:
106
109
  """Server port proposal generator. Starts with a linear search, then
107
110
  switches to a randomized search (random permutation of remaining ports).
108
111
  """
@@ -167,7 +170,7 @@ class BackgroundAppServer(threading.Thread):
167
170
 
168
171
  return self._server
169
172
 
170
- def __init__(self, *, host: str, base_port: int, max_port: int, app: Callable,
173
+ def __init__(self, *, host: str, base_port: int, max_port: int, app: abc.Callable,
171
174
  linear_tries: int = 1, randomized_tries: Optional[int] = None,
172
175
  timeout: Optional[float] = 10):
173
176
  super().__init__(daemon=True)
@@ -285,7 +288,7 @@ class RequestCaptureApp:
285
288
  if hasattr(self, '_exc') and self._exc:
286
289
  raise self._exc
287
290
 
288
- def __call__(self, environ: dict, start_response: Callable):
291
+ def __call__(self, environ: dict, start_response: abc.Callable):
289
292
  self.store_request(environ)
290
293
 
291
294
  start_response("200 OK", [('Content-Type', 'text/plain; charset=utf-8')])
@@ -298,14 +301,14 @@ class RequestCaptureAndRedirectApp(RequestCaptureApp):
298
301
  """
299
302
 
300
303
  def __init__(self, message: str,
301
- redirect_uri: Union[str, Callable],
304
+ redirect_uri: Union[str, abc.Callable],
302
305
  include_query: bool = True):
303
306
  super().__init__(message)
304
307
 
305
308
  self.redirect_uri = redirect_uri
306
309
  self.include_query = include_query
307
310
 
308
- def __call__(self, environ: dict, start_response: Callable):
311
+ def __call__(self, environ: dict, start_response: abc.Callable):
309
312
  self.store_request(environ)
310
313
 
311
314
  if callable(self.redirect_uri):
@@ -17,12 +17,12 @@ import sys
17
17
  import ast
18
18
  import orjson
19
19
  import subprocess
20
- from collections.abc import Sequence
20
+ from collections import abc
21
21
  from configparser import ConfigParser
22
22
  from datetime import datetime
23
23
  from functools import wraps, partial
24
24
  from timeit import default_timer as timer
25
- from typing import Callable, Dict, Optional, Tuple
25
+ from typing import Optional
26
26
 
27
27
  import click
28
28
  import requests.exceptions
@@ -37,7 +37,6 @@ from dwave.cloud.utils.http import user_agent
37
37
  from dwave.cloud.utils.logging import configure_logging
38
38
  from dwave.cloud.utils.qubo import generate_random_ising_problem
39
39
  from dwave.cloud.utils.time import datetime_to_timestamp, utcnow, epochnow
40
- from dwave.cloud.coders import bqm_as_file
41
40
  from dwave.cloud.package_info import __title__, __version__
42
41
  from dwave.cloud.exceptions import (
43
42
  SolverAuthenticationError, InvalidAPIResponseError, UnsupportedSolverError,
@@ -124,6 +123,15 @@ def json_output(fn):
124
123
  return fn
125
124
 
126
125
 
126
+ def raw_output(fn):
127
+ """Decorate `fn` with `--raw` option."""
128
+
129
+ fn = click.option('--raw', 'raw_output', default=False, is_flag=True,
130
+ help='Raw output')(fn)
131
+
132
+ return fn
133
+
134
+
127
135
  @click.group()
128
136
  @click.version_option(prog_name=__title__, version=__version__)
129
137
  @click.option('--debug', is_flag=True, callback=enable_logging,
@@ -207,7 +215,7 @@ def create(*, config_file, profile, ask_full, auto_token, project):
207
215
 
208
216
  def _input_config_variables(config: ConfigParser,
209
217
  profile: str,
210
- prompts: Dict[str, Dict[str, str]]) -> ConfigParser:
218
+ prompts: dict[str, dict[str, str]]) -> ConfigParser:
211
219
  """Update config variables in place with user-provided values."""
212
220
 
213
221
  for var, prompt in prompts.items():
@@ -420,20 +428,30 @@ def standardized_output(fn):
420
428
  def wrapped(*args, **kwargs):
421
429
  # text/json output taken from callee args
422
430
  json_output = kwargs.get('json_output', False)
431
+ raw_output = kwargs.get('raw_output', False)
423
432
 
424
433
  now = utcnow()
425
434
  info = dict(datetime=now.isoformat(), timestamp=datetime_to_timestamp(now), code=0)
426
435
 
427
- def output(fmt, maxlen=None, **params):
428
- info.update(params)
429
- if not json_output:
430
- msg = fmt.format(**params)
436
+ def output(fmt=None, maxlen=None, **params):
437
+ raw = params.pop('raw', None)
438
+ if raw_output:
439
+ if raw is not None:
440
+ click.echo(raw)
441
+ elif json_output:
442
+ info.update(params)
443
+ else:
444
+ if fmt is not None:
445
+ msg = fmt.format(**params)
446
+ else:
447
+ # logfmt-like output
448
+ msg = ' '.join(f'{k}={v}' for k,v in params.items())
431
449
  if maxlen is not None:
432
450
  msg = strtrunc(msg, maxlen)
433
451
  click.echo(msg)
434
452
 
435
453
  def flush():
436
- if json_output:
454
+ if json_output and not raw_output:
437
455
  click.echo(orjson.dumps(info))
438
456
 
439
457
  try:
@@ -652,7 +670,7 @@ def sample(*, config_file, profile, endpoint, region, client_type, solver_def,
652
670
  else:
653
671
  try:
654
672
  linear = ast.literal_eval(biases) if biases else {}
655
- if isinstance(linear, Sequence):
673
+ if isinstance(linear, abc.Sequence):
656
674
  linear = dict(enumerate(linear))
657
675
  except Exception as e:
658
676
  raise CLIError(f"Invalid biases: {e}", code=99)
@@ -734,7 +752,7 @@ def upload(config_file, profile, endpoint, region, client_type, solver_def,
734
752
  # fallback to reopen for now
735
753
  with open(input_file.name, 'rt') as fp:
736
754
  bqm = dimod.BinaryQuadraticModel.from_coo(fp)
737
- problem_file = bqm_as_file(bqm)
755
+ problem_file = bqm.to_file()
738
756
 
739
757
  elif format == 'dimodbqm':
740
758
  problem_file = input_file
@@ -748,6 +766,8 @@ def upload(config_file, profile, endpoint, region, client_type, solver_def,
748
766
  except Exception as e:
749
767
  click.echo(e)
750
768
  return 2
769
+ finally:
770
+ problem_file.close()
751
771
 
752
772
  click.echo("Upload done. Problem ID: {!r}".format(remote_problem_id))
753
773
 
@@ -1003,8 +1023,9 @@ def _login(*, config_file, profile, oob, skip_valid, output):
1003
1023
  @click.argument('token_type', default='access-token',
1004
1024
  type=click.Choice(['access-token', 'refresh-token', 'id-token']))
1005
1025
  @json_output
1026
+ @raw_output
1006
1027
  @standardized_output
1007
- def get(*, config_file, profile, token_type, json_output, output):
1028
+ def get(*, config_file, profile, token_type, json_output, raw_output, output):
1008
1029
  """Fetch Leap API token."""
1009
1030
 
1010
1031
  config = validate_config_v1(load_config(config_file=config_file, profile=profile))
@@ -1015,7 +1036,9 @@ def get(*, config_file, profile, token_type, json_output, output):
1015
1036
  raise CLIError('Token not found. Please run "dwave auth login".', code=100)
1016
1037
 
1017
1038
  token_pretty = token_type.replace('-', ' ').capitalize()
1018
- output(f"{token_pretty}: {{%s}}" % token_key, **{token_key: flow.token[token_key]})
1039
+ token_val = flow.token[token_key]
1040
+ output(f"{token_pretty}: {{%s}}" % token_key, **{token_key: token_val})
1041
+ output(raw=token_val)
1019
1042
 
1020
1043
  if token_type == 'access-token':
1021
1044
  expires_at = flow.token.get('expires_at')
@@ -1119,8 +1142,9 @@ def list_leap_projects(*, config_file, profile, json_output, output):
1119
1142
  @click.option('--project', 'project_hint', type=str, default=None,
1120
1143
  help='Leap project ID, name or code. If unspecified, currently active project is used.')
1121
1144
  @json_output
1145
+ @raw_output
1122
1146
  @standardized_output
1123
- def leap_project_token(*, config_file, profile, project_hint, json_output, output):
1147
+ def leap_project_token(*, config_file, profile, project_hint, json_output, raw_output, output):
1124
1148
  """Get Solver API token for a selected Leap project."""
1125
1149
 
1126
1150
  project, token = _get_sapi_token_for_leap_project(
@@ -1128,12 +1152,12 @@ def leap_project_token(*, config_file, profile, project_hint, json_output, outpu
1128
1152
  project_hint=project_hint, output=output)
1129
1153
 
1130
1154
  output(f"Solver API token for project {project.name} ({project.code}) is {token}.",
1131
- token=token, project=project.model_dump())
1155
+ token=token, project=project.model_dump(), raw=token)
1132
1156
 
1133
1157
 
1134
1158
  def _get_sapi_token_for_leap_project(
1135
1159
  *, config_file: str, profile: str,
1136
- project_hint: Optional[str], output: Callable) -> Tuple[api.models.LeapProject, str]:
1160
+ project_hint: Optional[str], output: abc.Callable) -> tuple[api.models.LeapProject, str]:
1137
1161
 
1138
1162
  config = validate_config_v1(load_config(config_file=config_file, profile=profile))
1139
1163
  flow = LeapAuthFlow.from_config_model(config)