From 2dd1af75902e352c2f6538c80fbadaf3080fe45e Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Sun, 28 Aug 2022 09:55:24 +0200 Subject: [PATCH 01/36] deprecate_arguments and deprecate_function: add a deprecation note box --- qiskit/circuit/quantumcircuit.py | 5 ++-- qiskit/utils/deprecation.py | 46 ++++++++++++++++++++++++++++++-- 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py index 60ba8b80c6f3..fc7113ab72a4 100644 --- a/qiskit/circuit/quantumcircuit.py +++ b/qiskit/circuit/quantumcircuit.py @@ -716,10 +716,11 @@ def control( @deprecate_function( "The QuantumCircuit.combine() method is being deprecated. " "Use the compose() method which is more flexible w.r.t " - "circuit register compatibility." + "circuit register compatibility.", + docstring_version="0.17.0", ) def combine(self, rhs: "QuantumCircuit") -> "QuantumCircuit": - """DEPRECATED - Returns rhs appended to self if self contains compatible registers. + """Returns rhs appended to self if self contains compatible registers. Two circuits are compatible if they contain the same registers or if they contain different registers with unique names. The diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index 1a73803ab4f3..92816c0df9fc 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -16,10 +16,17 @@ import warnings -def deprecate_arguments(kwarg_map): +def deprecate_arguments(kwarg_map, docstring_version=None): """Decorator to automatically alias deprecated argument names and warn upon use.""" def decorator(func): + if docstring_version and kwarg_map: + msg = ["One or more keyword argument are being deprecated:", ""] + for old_arg, new_arg in kwarg_map.items(): + msg.append("* The argument {} is being replaced with {}".format(old_arg, new_arg)) + msg.append("") # Finish with an empty line + _extend_docstring(func, msg, docstring_version) + @functools.wraps(func) def wrapper(*args, **kwargs): if kwargs: @@ -31,18 +38,23 @@ def wrapper(*args, **kwargs): return decorator -def deprecate_function(msg, stacklevel=2): +def deprecate_function(msg, stacklevel=2, docstring_version=None): """Emit a warning prior to calling decorated function. Args: msg (str): Warning message to emit. stacklevel (int): The warning stackevel to use, defaults to 2. + docstring_version (str): If a version number, extends the docstring with a deprecation warning + box. If `None`, no docstring box will be added. Default: None Returns: Callable: The decorated, deprecated callable. """ def decorator(func): + if docstring_version: + _extend_docstring(func, msg.expandtabs().splitlines(), docstring_version) + @functools.wraps(func) def wrapper(*args, **kwargs): warnings.warn(msg, DeprecationWarning, stacklevel=stacklevel) @@ -67,3 +79,33 @@ def _rename_kwargs(func_name, kwargs, kwarg_map): ) kwargs[new_arg] = kwargs.pop(old_arg) + + +def _extend_docstring(func, msg_lines, version): + docstr = func.__doc__ + if docstr: + docstr_lines = docstr.expandtabs().splitlines() + else: + docstr_lines = ["DEPRECATED"] + indent = 1000 + first_empty_line = None + for line_no, line in enumerate(docstr_lines[1:], start=1): + stripped = line.lstrip() + if stripped: + indent = min(indent, len(line) - len(stripped)) + else: + if first_empty_line is None: + first_empty_line = line_no + if first_empty_line is None: + first_empty_line = len(docstr_lines) + spaces = "" + if indent != 1000: + spaces = " " * indent + + new_doc_str_lines = docstr_lines[:first_empty_line] + [ + "", + spaces + f".. deprecated:: {version}", + ] + for msg_line in msg_lines: + new_doc_str_lines.append(spaces + " " + msg_line) + func.__doc__ = "\n".join(new_doc_str_lines + docstr_lines[first_empty_line:]) From 82a1111b6d560e018e4aef62edf5ae6df7e531ad Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Sun, 4 Sep 2022 11:32:13 +0200 Subject: [PATCH 02/36] linting --- qiskit/utils/deprecation.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index eac5bc536923..50fd723d2919 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -17,7 +17,9 @@ from typing import Type -def deprecate_arguments(kwarg_map, category: Type[Warning] = DeprecationWarning, docstring_version=None): +def deprecate_arguments( + kwarg_map, category: Type[Warning] = DeprecationWarning, docstring_version=None +): """Decorator to automatically alias deprecated argument names and warn upon use.""" def decorator(func): @@ -39,7 +41,12 @@ def wrapper(*args, **kwargs): return decorator -def deprecate_function(msg: str, stacklevel: int = 2, category: Type[Warning] = DeprecationWarning, docstring_version: str=None): +def deprecate_function( + msg: str, + stacklevel: int = 2, + category: Type[Warning] = DeprecationWarning, + docstring_version: str = None, +): """Emit a warning prior to calling decorated function. Args: @@ -118,4 +125,4 @@ def _extend_docstring(func, msg_lines, version): ] for msg_line in msg_lines: new_doc_str_lines.append(spaces + " " + msg_line) - func.__doc__ = "\n".join(new_doc_str_lines + docstr_lines[first_empty_line:]) \ No newline at end of file + func.__doc__ = "\n".join(new_doc_str_lines + docstr_lines[first_empty_line:]) From 8efdcf6f2ffe1c493b7d8a881ac4b1230762e72f Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Sun, 4 Sep 2022 12:44:27 +0200 Subject: [PATCH 03/36] testing --- test/python/utils/test_deprecation.py | 107 ++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 test/python/utils/test_deprecation.py diff --git a/test/python/utils/test_deprecation.py b/test/python/utils/test_deprecation.py new file mode 100644 index 000000000000..cdf013843199 --- /dev/null +++ b/test/python/utils/test_deprecation.py @@ -0,0 +1,107 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2022. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Tests for the methods in ``utils.deprecation``.""" + + +from qiskit import QiskitError +from qiskit.utils.deprecation import deprecate_function, deprecate_arguments +from qiskit.test import QiskitTestCase + + +class DummyClass: + """This is short description. Let's make it + multiline""" + + def __init__(self, arg1: int = None, arg2: [int] = None): + self.arg1 = arg1 + self.arg2 = arg2 + + @deprecate_function( + "The DummyClass.foo() method is being deprecated. " "Use the DummyClass.some_othermethod()", + docstring_version="1.2.3", + ) + def foo_deprecated(self, index_arg2: int): + """A multi-line + docstring. + + Here are more details. + + Args: + index_arg2: `index_arg2` description + + Returns: + int: returns `arg2[index_arg2]` + + Raises: + QiskitError: if `len(self.arg2) < index_arg2` + """ + if len(self.arg2) < index_arg2: + raise QiskitError("there is an error") + return self.arg2[index_arg2] + + @deprecate_arguments({"if_arg1": "other_if_arg1"}) + def bar_with_deprecated_arg( + self, if_arg1: int = None, index_arg2: int = None, other_if_arg1: int = None + ): + """ + A multi-line short + docstring. + + This is the long description + + Args: + if_arg1: `if_arg1` description + index_arg2: `index_arg2` description + other_if_arg1: `other_if_arg1` description + + Returns: + int or None: if `if_arg1 == self.arg1`, returns `arg2[index_arg2]` + """ + if other_if_arg1 == self.arg1 or if_arg1 == self.arg1: + return self.arg2[index_arg2] + return None + + +class TestDeprecation(QiskitTestCase): + """Test deprecation decorators.""" + + def assertDeprecationWarning(self, warn, expected_msg): + """Checks there only one exception and `expected_msg` is the message""" + self.assertEqual(len(warn.warnings), 1) + self.assertEqual(len(warn.warnings[0].message.args), 1) + self.assertEqual(warn.warnings[0].message.args[0], expected_msg) + + def test_raise_deprecate_function(self): + """Test deprecate_function raises.""" + + dummy = DummyClass(arg2=[1, 2, 3]) + with self.assertWarns(DeprecationWarning) as warn: + output = dummy.foo_deprecated(0) + self.assertDeprecationWarning( + warn, + "The DummyClass.foo() method is being deprecated. Use the DummyClass.some_othermethod()", + ) + self.assertEqual(output, 1) + + def test_raise_deprecate_arguments(self): + """Test deprecate_arguments raises.""" + + dummy = DummyClass(arg1=3, arg2=[1, 2, 3]) + with self.assertWarns(DeprecationWarning) as warn: + output = dummy.bar_with_deprecated_arg(if_arg1=3, index_arg2=0) + self.assertDeprecationWarning( + warn, + "bar_with_deprecated_arg keyword argument if_arg1 is deprecated and replaced" + " with other_if_arg1.", + ) + self.assertEqual(output, 1) From 51e7e72d9b3ddb007cb99fb35199815bec998037 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Sun, 4 Sep 2022 13:02:42 +0200 Subject: [PATCH 04/36] testing docstrings --- test/python/utils/test_deprecation.py | 49 ++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/test/python/utils/test_deprecation.py b/test/python/utils/test_deprecation.py index cdf013843199..cd2b1c03ba1b 100644 --- a/test/python/utils/test_deprecation.py +++ b/test/python/utils/test_deprecation.py @@ -60,7 +60,8 @@ def bar_with_deprecated_arg( This is the long description Args: - if_arg1: `if_arg1` description + if_arg1: `if_arg1` description with + multi-line index_arg2: `index_arg2` description other_if_arg1: `other_if_arg1` description @@ -105,3 +106,49 @@ def test_raise_deprecate_arguments(self): " with other_if_arg1.", ) self.assertEqual(output, 1) + + def test_docstring_deprecate_function(self): + """Test deprecate_function docstring.""" + + dummy = DummyClass() + deprecated_docstring = dummy.foo_deprecated.__doc__ + expected = """A multi-line + docstring. + + .. deprecated:: 1.2.3 + The DummyClass.foo() method is being deprecated. Use the DummyClass.some_othermethod() + + Here are more details. + + Args: + index_arg2: `index_arg2` description + + Returns: + int: returns `arg2[index_arg2]` + + Raises: + QiskitError: if `len(self.arg2) < index_arg2` + """ + self.assertEqual(deprecated_docstring, expected) + + def test_docstring_deprecate_arguments(self): + """Test deprecate_arguments docstring.""" + + dummy = DummyClass() + deprecated_docstring = dummy.bar_with_deprecated_arg.__doc__ + expected = """ + A multi-line short + docstring. + + This is the long description + + Args: + if_arg1: `if_arg1` description with + multi-line + index_arg2: `index_arg2` description + other_if_arg1: `other_if_arg1` description + + Returns: + int or None: if `if_arg1 == self.arg1`, returns `arg2[index_arg2]` + """ + self.assertEqual(deprecated_docstring, expected) From 18bd25d9c7837d8f7cba3d729fc4bb83a8a301e9 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 5 Sep 2022 14:27:49 +0200 Subject: [PATCH 05/36] deprecate parameter in the parameter description --- qiskit/utils/deprecation.py | 64 +++++++++++++++++++++------ test/python/utils/test_deprecation.py | 9 ++-- 2 files changed, 56 insertions(+), 17 deletions(-) diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index 50fd723d2919..52ff503126ee 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -24,11 +24,7 @@ def deprecate_arguments( def decorator(func): if docstring_version and kwarg_map: - msg = ["One or more keyword argument are being deprecated:", ""] - for old_arg, new_arg in kwarg_map.items(): - msg.append("* The argument {} is being replaced with {}".format(old_arg, new_arg)) - msg.append("") # Finish with an empty line - _extend_docstring(func, msg, docstring_version) + _extend_docstring(func, docstring_version, kwarg_map) @functools.wraps(func) def wrapper(*args, **kwargs): @@ -62,7 +58,7 @@ def deprecate_function( def decorator(func): if docstring_version: - _extend_docstring(func, msg.expandtabs().splitlines(), docstring_version) + _extend_docstring(func, docstring_version, {None: msg.expandtabs().splitlines()}) @functools.wraps(func) def wrapper(*args, **kwargs): @@ -98,12 +94,15 @@ def _rename_kwargs(func_name, kwargs, kwarg_map, category: Type[Warning] = Depre kwargs[new_arg] = kwargs.pop(old_arg) -def _extend_docstring(func, msg_lines, version): +def _extend_docstring(func, version, kwarg_map): + """kwarg_map[None] means message in no kwarg, and it will be + append to the long desscription""" docstr = func.__doc__ if docstr: docstr_lines = docstr.expandtabs().splitlines() else: docstr_lines = ["DEPRECATED"] + indent = 1000 first_empty_line = None for line_no, line in enumerate(docstr_lines[1:], start=1): @@ -119,10 +118,47 @@ def _extend_docstring(func, msg_lines, version): if indent != 1000: spaces = " " * indent - new_doc_str_lines = docstr_lines[:first_empty_line] + [ - "", - spaces + f".. deprecated:: {version}", - ] - for msg_line in msg_lines: - new_doc_str_lines.append(spaces + " " + msg_line) - func.__doc__ = "\n".join(new_doc_str_lines + docstr_lines[first_empty_line:]) + new_doc_str_lines = docstr_lines[:first_empty_line] + if None in kwarg_map: + new_doc_str_lines += ["", spaces + f".. deprecated:: {version}"] + for msg_line in kwarg_map[None]: + new_doc_str_lines.append(spaces + " " + msg_line) + + arg_indent = indent + args_section = False + deprecated_arg = False + for docstr_line in docstr_lines[first_empty_line:]: + stripped = docstr_line.lstrip() + current_indent = len(docstr_line) - len(stripped) + if args_section: + if deprecated_arg and current_indent == arg_indent: + new_doc_str_lines.append(docstr_line) + deprecated_arg = False + else: + if not deprecated_arg: + for k in kwarg_map.keys(): + if k is None: + continue + if stripped.startswith(k): + arg_indent = len(docstr_line) - len(stripped) + deprecated_arg = True + spaces = " " * arg_indent + new_doc_str_lines.append(spaces + k + ":") + spaces += " " * 4 + new_doc_str_lines += [ + spaces + f".. deprecated:: {version}", + spaces + f" The keyword argument `{k}` is deprecated.", + spaces + f" Please, use `{kwarg_map[k]}` instead.", + "", + ] + break + else: + new_doc_str_lines.append(docstr_line) + else: + new_doc_str_lines.append(docstr_line) + if docstr_line.lstrip() == "Args:": + args_section = True + if args_section and docstr_line.lstrip() == "": + args_section = False + + func.__doc__ = "\n".join(new_doc_str_lines) diff --git a/test/python/utils/test_deprecation.py b/test/python/utils/test_deprecation.py index cd2b1c03ba1b..82312dc7c86a 100644 --- a/test/python/utils/test_deprecation.py +++ b/test/python/utils/test_deprecation.py @@ -49,7 +49,7 @@ def foo_deprecated(self, index_arg2: int): raise QiskitError("there is an error") return self.arg2[index_arg2] - @deprecate_arguments({"if_arg1": "other_if_arg1"}) + @deprecate_arguments({"if_arg1": "other_if_arg1"}, docstring_version="1.2.3") def bar_with_deprecated_arg( self, if_arg1: int = None, index_arg2: int = None, other_if_arg1: int = None ): @@ -143,8 +143,11 @@ def test_docstring_deprecate_arguments(self): This is the long description Args: - if_arg1: `if_arg1` description with - multi-line + if_arg1: + .. deprecated:: 1.2.3 + The keyword argument `if_arg1` is deprecated. + Please, use `other_if_arg1` instead. + index_arg2: `index_arg2` description other_if_arg1: `other_if_arg1` description From 4fc029c97ef188dbb6a014fdd138b9caed413f90 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 6 Sep 2022 22:01:56 +0200 Subject: [PATCH 06/36] deprecate_arguments --- qiskit/transpiler/passes/basis/decompose.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qiskit/transpiler/passes/basis/decompose.py b/qiskit/transpiler/passes/basis/decompose.py index 062e97558cfb..6f4d23f7684f 100644 --- a/qiskit/transpiler/passes/basis/decompose.py +++ b/qiskit/transpiler/passes/basis/decompose.py @@ -25,7 +25,7 @@ class Decompose(TransformationPass): """Expand a gate in a circuit using its decomposition rules.""" - @deprecate_arguments({"gate": "gates_to_decompose"}) + @deprecate_arguments({"gate": "gates_to_decompose"}, docstring_version="0.19.0") def __init__( self, gate: Optional[Type[Gate]] = None, From da68919e3723c9d0f57562e35f0bdd3e50be81e7 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 7 Sep 2022 11:50:26 +0200 Subject: [PATCH 07/36] implementing all the deprecate_function --- qiskit/algorithms/factorizers/shor.py | 3 ++- qiskit/algorithms/linear_solvers/hhl.py | 3 ++- .../linear_solvers/linear_solver.py | 6 ++++-- .../matrices/linear_system_matrix.py | 3 ++- .../linear_solvers/matrices/numpy_matrix.py | 3 ++- .../matrices/tridiagonal_toeplitz.py | 3 ++- .../linear_solvers/numpy_linear_solver.py | 3 ++- .../observables/absolute_average.py | 3 ++- .../observables/linear_system_observable.py | 3 ++- .../observables/matrix_functional.py | 3 ++- qiskit/algorithms/optimizers/spsa.py | 3 ++- .../phase_estimation_result.py | 3 ++- qiskit/circuit/quantumcircuit.py | 21 ++++++++++++------- qiskit/dagcircuit/dagcircuit.py | 9 +++++--- qiskit/primitives/base_estimator.py | 5 ++++- qiskit/scheduler/utils.py | 16 +++++++------- qiskit/utils/deprecation.py | 4 ++-- 17 files changed, 61 insertions(+), 33 deletions(-) diff --git a/qiskit/algorithms/factorizers/shor.py b/qiskit/algorithms/factorizers/shor.py index 06f9f1610e09..662832de9f55 100644 --- a/qiskit/algorithms/factorizers/shor.py +++ b/qiskit/algorithms/factorizers/shor.py @@ -58,7 +58,8 @@ class Shor: @deprecate_function( "The Shor class is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the release date. " + "and will be removed no sooner than 3 months after the release date. ", + docstring_version="0.22.0", ) def __init__(self, quantum_instance: Optional[Union[QuantumInstance, Backend]] = None) -> None: """ diff --git a/qiskit/algorithms/linear_solvers/hhl.py b/qiskit/algorithms/linear_solvers/hhl.py index c5bf52a0380d..c803e5f29517 100644 --- a/qiskit/algorithms/linear_solvers/hhl.py +++ b/qiskit/algorithms/linear_solvers/hhl.py @@ -105,7 +105,8 @@ class HHL(LinearSolver): @deprecate_function( "The HHL class is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the release date. " + "and will be removed no sooner than 3 months after the release date. ", + docstring_version="0.22.0", ) def __init__( self, diff --git a/qiskit/algorithms/linear_solvers/linear_solver.py b/qiskit/algorithms/linear_solvers/linear_solver.py index 97a68226ebb9..743bce2ddace 100644 --- a/qiskit/algorithms/linear_solvers/linear_solver.py +++ b/qiskit/algorithms/linear_solvers/linear_solver.py @@ -34,7 +34,8 @@ class LinearSolverResult(AlgorithmResult): @deprecate_function( "The LinearSolverResult class is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the release date. " + "and will be removed no sooner than 3 months after the release date. ", + docstring_version="0.22.0", ) def __init__(self) -> None: super().__init__() @@ -102,7 +103,8 @@ class LinearSolver(ABC): @deprecate_function( "The LinearSolver class is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the release date. " + "and will be removed no sooner than 3 months after the release date. ", + docstring_version="0.22.0", ) def __init__(self) -> None: pass diff --git a/qiskit/algorithms/linear_solvers/matrices/linear_system_matrix.py b/qiskit/algorithms/linear_solvers/matrices/linear_system_matrix.py index 26e53860dc1f..c295faffba11 100644 --- a/qiskit/algorithms/linear_solvers/matrices/linear_system_matrix.py +++ b/qiskit/algorithms/linear_solvers/matrices/linear_system_matrix.py @@ -25,7 +25,8 @@ class LinearSystemMatrix(BlueprintCircuit, ABC): @deprecate_function( "The LinearSystemMatrix class is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the release date. " + "and will be removed no sooner than 3 months after the release date. ", + docstring_version="0.22.0", ) def __init__( self, diff --git a/qiskit/algorithms/linear_solvers/matrices/numpy_matrix.py b/qiskit/algorithms/linear_solvers/matrices/numpy_matrix.py index fdf30017c925..21edf50850f1 100644 --- a/qiskit/algorithms/linear_solvers/matrices/numpy_matrix.py +++ b/qiskit/algorithms/linear_solvers/matrices/numpy_matrix.py @@ -50,7 +50,8 @@ class NumPyMatrix(LinearSystemMatrix): @deprecate_function( "The NumPyMatrix class is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the release date. " + "and will be removed no sooner than 3 months after the release date. ", + docstring_version="0.22.0", ) def __init__( self, diff --git a/qiskit/algorithms/linear_solvers/matrices/tridiagonal_toeplitz.py b/qiskit/algorithms/linear_solvers/matrices/tridiagonal_toeplitz.py index 6dda2716b680..a1027f432b7b 100644 --- a/qiskit/algorithms/linear_solvers/matrices/tridiagonal_toeplitz.py +++ b/qiskit/algorithms/linear_solvers/matrices/tridiagonal_toeplitz.py @@ -62,7 +62,8 @@ class TridiagonalToeplitz(LinearSystemMatrix): @deprecate_function( "The TridiagonalToeplitz class is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the release date. " + "and will be removed no sooner than 3 months after the release date. ", + docstring_version="0.22.0", ) def __init__( self, diff --git a/qiskit/algorithms/linear_solvers/numpy_linear_solver.py b/qiskit/algorithms/linear_solvers/numpy_linear_solver.py index 0a3cbbd57191..bafcfe5133a5 100644 --- a/qiskit/algorithms/linear_solvers/numpy_linear_solver.py +++ b/qiskit/algorithms/linear_solvers/numpy_linear_solver.py @@ -55,7 +55,8 @@ class NumPyLinearSolver(LinearSolver): @deprecate_function( "The NumPyLinearSolver class is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the release date. " + "and will be removed no sooner than 3 months after the release date. ", + docstring_version="0.22.0", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/algorithms/linear_solvers/observables/absolute_average.py b/qiskit/algorithms/linear_solvers/observables/absolute_average.py index 300c31edaed9..994260e1afe7 100644 --- a/qiskit/algorithms/linear_solvers/observables/absolute_average.py +++ b/qiskit/algorithms/linear_solvers/observables/absolute_average.py @@ -65,7 +65,8 @@ class AbsoluteAverage(LinearSystemObservable): @deprecate_function( "The AbsoluteAverage class is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the release date. " + "and will be removed no sooner than 3 months after the release date. ", + docstring_version="0.22.0", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/algorithms/linear_solvers/observables/linear_system_observable.py b/qiskit/algorithms/linear_solvers/observables/linear_system_observable.py index fd6ea2339738..e55227de4538 100644 --- a/qiskit/algorithms/linear_solvers/observables/linear_system_observable.py +++ b/qiskit/algorithms/linear_solvers/observables/linear_system_observable.py @@ -26,7 +26,8 @@ class LinearSystemObservable(ABC): @deprecate_function( "The LinearSystemObservable class is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the release date. " + "and will be removed no sooner than 3 months after the release date. ", + docstring_version="0.22.0", ) def __init__(self) -> None: pass diff --git a/qiskit/algorithms/linear_solvers/observables/matrix_functional.py b/qiskit/algorithms/linear_solvers/observables/matrix_functional.py index ca0cfecf16bc..250282f49369 100644 --- a/qiskit/algorithms/linear_solvers/observables/matrix_functional.py +++ b/qiskit/algorithms/linear_solvers/observables/matrix_functional.py @@ -77,7 +77,8 @@ class MatrixFunctional(LinearSystemObservable): @deprecate_function( "The MatrixFunctional class is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the release date. " + "and will be removed no sooner than 3 months after the release date. ", + docstring_version="0.22.0", ) def __init__(self, main_diag: float, off_diag: int) -> None: """ diff --git a/qiskit/algorithms/optimizers/spsa.py b/qiskit/algorithms/optimizers/spsa.py index 10d81dfdd41c..d4cccf813d56 100644 --- a/qiskit/algorithms/optimizers/spsa.py +++ b/qiskit/algorithms/optimizers/spsa.py @@ -651,7 +651,8 @@ def get_support_level(self): "The SPSA.optimize method is deprecated as of Qiskit Terra 0.21.0 and will be removed no " "sooner than 3 months after the release date. Instead, use SPSA.minimize as a replacement, " "which supports the same arguments but follows the interface of scipy.optimize and returns " - "a complete result object containing additional information." + "a complete result object containing additional information.", + docstring_version="0.21.0", ) def optimize( self, diff --git a/qiskit/algorithms/phase_estimators/phase_estimation_result.py b/qiskit/algorithms/phase_estimators/phase_estimation_result.py index d9606fe03f65..ffc114d66a13 100644 --- a/qiskit/algorithms/phase_estimators/phase_estimation_result.py +++ b/qiskit/algorithms/phase_estimators/phase_estimation_result.py @@ -71,7 +71,8 @@ def circuit_result(self) -> Result: @deprecate_function( """The 'PhaseEstimationResult.most_likely_phase' attribute is deprecated as of 0.18.0 and will be removed no earlier than 3 months - after the release date. It has been renamed as the 'phase' attribute.""" + after the release date. It has been renamed as the 'phase' attribute.""", + docstring_version="0.18.0", ) def most_likely_phase(self) -> float: r"""DEPRECATED - Return the most likely phase as a number in :math:`[0.0, 1.0)`. diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py index f8fe2fdac0bd..28e278d16d4a 100644 --- a/qiskit/circuit/quantumcircuit.py +++ b/qiskit/circuit/quantumcircuit.py @@ -769,7 +769,8 @@ def combine(self, rhs: "QuantumCircuit") -> "QuantumCircuit": @deprecate_function( "The QuantumCircuit.extend() method is being deprecated. Use the " "compose() (potentially with the inplace=True argument) and tensor() " - "methods which are more flexible w.r.t circuit register compatibility." + "methods which are more flexible w.r.t circuit register compatibility.", + docstring_version="0.17.0", ) def extend(self, rhs: "QuantumCircuit") -> "QuantumCircuit": """DEPRECATED - Append QuantumCircuit to the RHS if it contains compatible registers. @@ -3766,7 +3767,8 @@ def cu( "0.16.0. It will be removed no earlier than 3 months " "after the release date. You should use the " "QuantumCircuit.p method instead, which acts " - "identically." + "identically.", + docstring_version="0.16.0", ) def u1(self, theta: ParameterValueType, qubit: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.U1Gate`. @@ -3789,7 +3791,8 @@ def u1(self, theta: ParameterValueType, qubit: QubitSpecifier) -> InstructionSet "0.16.0. It will be removed no earlier than 3 months " "after the release date. You should use the " "QuantumCircuit.cp method instead, which acts " - "identically." + "identically.", + docstring_version="0.16.0", ) def cu1( self, @@ -3826,7 +3829,8 @@ def cu1( "0.16.0. It will be removed no earlier than 3 months " "after the release date. You should use the " "QuantumCircuit.mcp method instead, which acts " - "identically." + "identically.", + docstring_version="0.16.0", ) def mcu1( self, @@ -3858,7 +3862,8 @@ def mcu1( "qubit gate QuantumCircuit.u instead: u2(φ,λ) = " "u(π/2, φ, λ). Alternatively, you can decompose it in" "terms of QuantumCircuit.p and QuantumCircuit.sx: " - "u2(φ,λ) = p(π/2+φ) sx p(λ-π/2) (1 pulse on hardware)." + "u2(φ,λ) = p(π/2+φ) sx p(λ-π/2) (1 pulse on hardware).", + docstring_version="0.16.0", ) def u2( self, phi: ParameterValueType, lam: ParameterValueType, qubit: QubitSpecifier @@ -3884,7 +3889,8 @@ def u2( "removed no earlier than 3 months after the release date. You should use " "QuantumCircuit.u instead, which acts identically. Alternatively, you can " "decompose u3 in terms of QuantumCircuit.p and QuantumCircuit.sx: " - "u3(ϴ,φ,λ) = p(φ+π) sx p(ϴ+π) sx p(λ) (2 pulses on hardware)." + "u3(ϴ,φ,λ) = p(φ+π) sx p(ϴ+π) sx p(λ) (2 pulses on hardware).", + docstring_version="0.16.0", ) def u3( self, @@ -3914,7 +3920,8 @@ def u3( "The QuantumCircuit.cu3 method is deprecated as of 0.16.0. It will be " "removed no earlier than 3 months after the release date. You should " "use the QuantumCircuit.cu method instead, where " - "cu3(ϴ,φ,λ) = cu(ϴ,φ,λ,0)." + "cu3(ϴ,φ,λ) = cu(ϴ,φ,λ,0).", + docstring_version="0.16.0", ) def cu3( self, diff --git a/qiskit/dagcircuit/dagcircuit.py b/qiskit/dagcircuit/dagcircuit.py index 3f0fa48be8dc..1850b85a3780 100644 --- a/qiskit/dagcircuit/dagcircuit.py +++ b/qiskit/dagcircuit/dagcircuit.py @@ -97,7 +97,8 @@ def __init__(self): @_optionals.HAS_NETWORKX.require_in_call @deprecate_function( - "The to_networkx() method is deprecated and will be removed in a future release." + "The to_networkx() method is deprecated and will be removed in a future release.", + docstring_version="0.21.0", ) def to_networkx(self): """Returns a copy of the DAGCircuit in networkx format.""" @@ -114,7 +115,8 @@ def to_networkx(self): @classmethod @_optionals.HAS_NETWORKX.require_in_call @deprecate_function( - "The from_networkx() method is deprecated and will be removed in a future release." + "The from_networkx() method is deprecated and will be removed in a future release.", + docstring_version="0.21.0", ) def from_networkx(cls, graph): """Take a networkx MultiDigraph and create a new DAGCircuit. @@ -503,7 +505,8 @@ def _add_op_node(self, op, qargs, cargs): """The DAGCircuit._copy_circuit_metadata method is deprecated as of 0.20.0. It will be removed no earlier than 3 months after the release date. You should use the DAGCircuit.copy_empty_like method instead, which acts identically. - """ + """, + docstring_version="0.20.0", ) def _copy_circuit_metadata(self): """DEPRECATED""" diff --git a/qiskit/primitives/base_estimator.py b/qiskit/primitives/base_estimator.py index 10be880f3f37..25b3c79b9616 100644 --- a/qiskit/primitives/base_estimator.py +++ b/qiskit/primitives/base_estimator.py @@ -219,8 +219,9 @@ def __new__( @deprecate_function( "The BaseEstimator.__enter__ method is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the releasedate. " + "and will be removed no sooner than 3 months after the release date. " "BaseEstimator should be initialized directly.", + docstring_version="0.22.0", ) def __enter__(self): return self @@ -229,6 +230,7 @@ def __enter__(self): "The BaseEstimator.__exit__ method is deprecated as of Qiskit Terra 0.22.0 " "and will be removed no sooner than 3 months after the releasedate. " "BaseEstimator should be initialized directly.", + docstring_version="0.22.0", ) def __exit__(self, *exc_info): self.close() @@ -285,6 +287,7 @@ def set_run_options(self, **fields) -> BaseEstimator: "The BaseSampler.__call__ method is deprecated as of Qiskit Terra 0.22.0 " "and will be removed no sooner than 3 months after the releasedate. " "Use run method instead.", + docstring_version="0.22.0", ) @deprecate_arguments({"circuit_indices": "circuits", "observable_indices": "observables"}) def __call__( diff --git a/qiskit/scheduler/utils.py b/qiskit/scheduler/utils.py index 5df6918dcb0b..a0a085070315 100644 --- a/qiskit/scheduler/utils.py +++ b/qiskit/scheduler/utils.py @@ -15,12 +15,14 @@ from qiskit.utils.deprecation import deprecate_function from qiskit.pulse import macros, utils -format_meas_map = deprecate_function('"format_meas_map" has been moved to "qiskit.pulse.utils"')( - utils.format_meas_map -) +format_meas_map = deprecate_function( + '"format_meas_map" has been moved to "qiskit.pulse.utils"', docstring_version="0.15.0" +)(utils.format_meas_map) -measure = deprecate_function('"measure" has been moved to "qiskit.pulse.macros"')(macros.measure) +measure = deprecate_function( + '"measure" has been moved to "qiskit.pulse.macros"', docstring_version="0.15.0" +)(macros.measure) -measure_all = deprecate_function('"measure_all" has been moved to "qiskit.pulse.macros"')( - macros.measure_all -) +measure_all = deprecate_function( + '"measure_all" has been moved to "qiskit.pulse.macros"', docstring_version="0.15.0" +)(macros.measure_all) diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index 52ff503126ee..7c51243fb107 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -147,8 +147,8 @@ def _extend_docstring(func, version, kwarg_map): spaces += " " * 4 new_doc_str_lines += [ spaces + f".. deprecated:: {version}", - spaces + f" The keyword argument `{k}` is deprecated.", - spaces + f" Please, use `{kwarg_map[k]}` instead.", + spaces + f" The keyword argument ``{k}`` is deprecated.", + spaces + f" Please, use ``{kwarg_map[k]}`` instead.", "", ] break From 071fa5db396b101a1fc86f91132581f5063cffdc Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 7 Sep 2022 12:27:42 +0200 Subject: [PATCH 08/36] ups. testing --- test/python/utils/test_deprecation.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/python/utils/test_deprecation.py b/test/python/utils/test_deprecation.py index 82312dc7c86a..aee071a40b87 100644 --- a/test/python/utils/test_deprecation.py +++ b/test/python/utils/test_deprecation.py @@ -145,8 +145,8 @@ def test_docstring_deprecate_arguments(self): Args: if_arg1: .. deprecated:: 1.2.3 - The keyword argument `if_arg1` is deprecated. - Please, use `other_if_arg1` instead. + The keyword argument ``if_arg1`` is deprecated. + Please, use ``other_if_arg1`` instead. index_arg2: `index_arg2` description other_if_arg1: `other_if_arg1` description From 397e33657f64759213342d4e0aea209bb9d96c19 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 7 Sep 2022 12:43:49 +0200 Subject: [PATCH 09/36] implement deprecate_arguments around --- qiskit/algorithms/optimizers/adam_amsgrad.py | 3 ++- qiskit/primitives/base_estimator.py | 9 ++++++--- qiskit/primitives/base_sampler.py | 8 ++++---- qiskit/qpy/interface.py | 2 +- qiskit/visualization/state_visualization.py | 10 +++++----- 5 files changed, 18 insertions(+), 14 deletions(-) diff --git a/qiskit/algorithms/optimizers/adam_amsgrad.py b/qiskit/algorithms/optimizers/adam_amsgrad.py index ee305e00f446..626b43f8fdd5 100644 --- a/qiskit/algorithms/optimizers/adam_amsgrad.py +++ b/qiskit/algorithms/optimizers/adam_amsgrad.py @@ -198,7 +198,8 @@ def load_params(self, load_dir: str) -> None: "objective_function": "fun", "initial_point": "x0", "gradient_function": "jac", - } + }, + docstring_version="0.19.0", ) # pylint: disable=arguments-differ def minimize( diff --git a/qiskit/primitives/base_estimator.py b/qiskit/primitives/base_estimator.py index 25b3c79b9616..452a7cb24791 100644 --- a/qiskit/primitives/base_estimator.py +++ b/qiskit/primitives/base_estimator.py @@ -228,7 +228,7 @@ def __enter__(self): @deprecate_function( "The BaseEstimator.__exit__ method is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the releasedate. " + "and will be removed no sooner than 3 months after the release date. " "BaseEstimator should be initialized directly.", docstring_version="0.22.0", ) @@ -285,11 +285,14 @@ def set_run_options(self, **fields) -> BaseEstimator: @deprecate_function( "The BaseSampler.__call__ method is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the releasedate. " + "and will be removed no sooner than 3 months after the release date. " "Use run method instead.", docstring_version="0.22.0", ) - @deprecate_arguments({"circuit_indices": "circuits", "observable_indices": "observables"}) + @deprecate_arguments( + {"circuit_indices": "circuits", "observable_indices": "observables"}, + docstring_version="0.21.0", + ) def __call__( self, circuits: Sequence[int | QuantumCircuit], diff --git a/qiskit/primitives/base_sampler.py b/qiskit/primitives/base_sampler.py index 6cd957996029..01e9e661ae3d 100644 --- a/qiskit/primitives/base_sampler.py +++ b/qiskit/primitives/base_sampler.py @@ -179,7 +179,7 @@ def __new__( @deprecate_function( "The BaseSampler.__enter__ method is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the releasedate. " + "and will be removed no sooner than 3 months after the release date. " "BaseSampler should be initialized directly.", ) def __enter__(self): @@ -187,7 +187,7 @@ def __enter__(self): @deprecate_function( "The BaseSampler.__exit__ method is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the releasedate. " + "and will be removed no sooner than 3 months after the release date. " "BaseSampler should be initialized directly.", ) def __exit__(self, *exc_info): @@ -234,10 +234,10 @@ def set_run_options(self, **fields) -> BaseSampler: @deprecate_function( "The BaseSampler.__call__ method is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the releasedate. " + "and will be removed no sooner than 3 months after the release date. " "Use run method instead.", ) - @deprecate_arguments({"circuit_indices": "circuits"}) + @deprecate_arguments({"circuit_indices": "circuits"}, docstring_version="0.21.0") def __call__( self, circuits: Sequence[int | QuantumCircuit], diff --git a/qiskit/qpy/interface.py b/qiskit/qpy/interface.py index 2e764e68bb70..7af31678701a 100644 --- a/qiskit/qpy/interface.py +++ b/qiskit/qpy/interface.py @@ -72,7 +72,7 @@ VERSION_PATTERN_REGEX = re.compile(VERSION_PATTERN, re.VERBOSE | re.IGNORECASE) -@deprecate_arguments({"circuits": "programs"}) +@deprecate_arguments({"circuits": "programs"}, docstring_version="0.21.0") def dump( programs: Union[List[QPY_SUPPORTED_TYPES], QPY_SUPPORTED_TYPES], file_obj: BinaryIO, diff --git a/qiskit/visualization/state_visualization.py b/qiskit/visualization/state_visualization.py index 40b38df245d2..30db1177acfd 100644 --- a/qiskit/visualization/state_visualization.py +++ b/qiskit/visualization/state_visualization.py @@ -36,7 +36,7 @@ from qiskit.circuit.tools.pi_check import pi_check -@deprecate_arguments({"rho": "state"}) +@deprecate_arguments({"rho": "state"}, docstring_version="0.15.1") @_optionals.HAS_MATPLOTLIB.require_in_call def plot_state_hinton( state, title="", figsize=None, ax_real=None, ax_imag=None, *, rho=None, filename=None @@ -243,7 +243,7 @@ def plot_bloch_vector(bloch, title="", ax=None, figsize=None, coord_type="cartes return None -@deprecate_arguments({"rho": "state"}) +@deprecate_arguments({"rho": "state"}, docstring_version="0.15.1") @_optionals.HAS_MATPLOTLIB.require_in_call def plot_bloch_multivector( state, title="", figsize=None, *, rho=None, reverse_bits=False, filename=None @@ -321,7 +321,7 @@ def plot_bloch_multivector( return fig.savefig(filename) -@deprecate_arguments({"rho": "state"}) +@deprecate_arguments({"rho": "state"}, docstring_version="0.15.1") @_optionals.HAS_MATPLOTLIB.require_in_call def plot_state_city( state, @@ -569,7 +569,7 @@ def plot_state_city( return fig.savefig(filename) -@deprecate_arguments({"rho": "state"}) +@deprecate_arguments({"rho": "state"}, docstring_version="0.15.1") @_optionals.HAS_MATPLOTLIB.require_in_call def plot_state_paulivec( state, title="", figsize=None, color=None, ax=None, *, rho=None, filename=None @@ -727,7 +727,7 @@ def phase_to_rgb(complex_number): return rgb -@deprecate_arguments({"rho": "state"}) +@deprecate_arguments({"rho": "state"}, docstring_version="0.15.1") @_optionals.HAS_MATPLOTLIB.require_in_call @_optionals.HAS_SEABORN.require_in_call def plot_state_qsphere( From fbc2d74925293b7c63df7586ba89765d7ccb318b Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 8 Sep 2022 13:50:14 +0200 Subject: [PATCH 10/36] ref to pep-0257 --- qiskit/utils/deprecation.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index 45e55773670d..86aa9f9f7b90 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -105,6 +105,9 @@ def _extend_docstring(func, version, kwarg_map): else: docstr_lines = ["DEPRECATED"] + # Mostly based on: + # https://peps.python.org/pep-0257/#handling-docstring-indentation + # --v-v-v-v-v-v-v-- indent = 1000 first_empty_line = None for line_no, line in enumerate(docstr_lines[1:], start=1): @@ -119,6 +122,7 @@ def _extend_docstring(func, version, kwarg_map): spaces = "" if indent != 1000: spaces = " " * indent + # --^-^-^-^-^-^-^-- new_doc_str_lines = docstr_lines[:first_empty_line] if None in kwarg_map: From def73fcf8f01ba5eb07c416f118ecc66665c0d45 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 8 Sep 2022 14:09:01 +0200 Subject: [PATCH 11/36] deprecation message on top of Args --- qiskit/utils/deprecation.py | 15 +++++++-------- test/python/utils/test_deprecation.py | 4 ++-- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index 86aa9f9f7b90..de5a56b5b8ae 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -109,22 +109,21 @@ def _extend_docstring(func, version, kwarg_map): # https://peps.python.org/pep-0257/#handling-docstring-indentation # --v-v-v-v-v-v-v-- indent = 1000 - first_empty_line = None + pre_args_line = None for line_no, line in enumerate(docstr_lines[1:], start=1): stripped = line.lstrip() if stripped: indent = min(indent, len(line) - len(stripped)) - else: - if first_empty_line is None: - first_empty_line = line_no - if first_empty_line is None: - first_empty_line = len(docstr_lines) + if line.lstrip() == "Args:" and pre_args_line is None: + pre_args_line = line_no - 1 + if pre_args_line is None: + pre_args_line = len(docstr_lines) spaces = "" if indent != 1000: spaces = " " * indent # --^-^-^-^-^-^-^-- - new_doc_str_lines = docstr_lines[:first_empty_line] + new_doc_str_lines = docstr_lines[:pre_args_line] if None in kwarg_map: new_doc_str_lines += ["", spaces + f".. deprecated:: {version}"] for msg_line in kwarg_map[None]: @@ -133,7 +132,7 @@ def _extend_docstring(func, version, kwarg_map): arg_indent = indent args_section = False deprecated_arg = False - for docstr_line in docstr_lines[first_empty_line:]: + for docstr_line in docstr_lines[pre_args_line:]: stripped = docstr_line.lstrip() current_indent = len(docstr_line) - len(stripped) if args_section: diff --git a/test/python/utils/test_deprecation.py b/test/python/utils/test_deprecation.py index aee071a40b87..a5c9dd0c48d2 100644 --- a/test/python/utils/test_deprecation.py +++ b/test/python/utils/test_deprecation.py @@ -115,11 +115,11 @@ def test_docstring_deprecate_function(self): expected = """A multi-line docstring. + Here are more details. + .. deprecated:: 1.2.3 The DummyClass.foo() method is being deprecated. Use the DummyClass.some_othermethod() - Here are more details. - Args: index_arg2: `index_arg2` description From 91c821d5e1345311fadea5e3502570246858cb99 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 8 Sep 2022 15:17:56 +0200 Subject: [PATCH 12/36] avoiding being ate by Lev --- test/python/utils/test_deprecation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/python/utils/test_deprecation.py b/test/python/utils/test_deprecation.py index a5c9dd0c48d2..e3a5b7b4f326 100644 --- a/test/python/utils/test_deprecation.py +++ b/test/python/utils/test_deprecation.py @@ -27,7 +27,7 @@ def __init__(self, arg1: int = None, arg2: [int] = None): self.arg2 = arg2 @deprecate_function( - "The DummyClass.foo() method is being deprecated. " "Use the DummyClass.some_othermethod()", + "The DummyClass.foo() method is being deprecated. Use the DummyClass.some_othermethod()", docstring_version="1.2.3", ) def foo_deprecated(self, index_arg2: int): From e5a22bcb8cd870364b92465368cedb0f1faf3bf2 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 22 Sep 2022 15:03:28 +0200 Subject: [PATCH 13/36] docstring --- qiskit/algorithms/aux_ops_evaluator.py | 1 + .../algorithms/evolvers/evolution_problem.py | 1 + qiskit/algorithms/factorizers/shor.py | 2 +- qiskit/algorithms/linear_solvers/hhl.py | 2 +- .../linear_solvers/linear_solver.py | 4 +-- .../matrices/linear_system_matrix.py | 2 +- .../linear_solvers/matrices/numpy_matrix.py | 2 +- .../matrices/tridiagonal_toeplitz.py | 2 +- .../linear_solvers/numpy_linear_solver.py | 2 +- .../observables/absolute_average.py | 2 +- .../observables/linear_system_observable.py | 2 +- .../observables/matrix_functional.py | 2 +- qiskit/algorithms/optimizers/adam_amsgrad.py | 2 +- qiskit/algorithms/optimizers/spsa.py | 2 +- .../phase_estimation_result.py | 2 +- qiskit/circuit/quantumcircuit.py | 22 +++++++++------- qiskit/dagcircuit/dagcircuit.py | 6 ++--- qiskit/primitives/base_estimator.py | 9 +++---- qiskit/primitives/base_sampler.py | 8 +++--- qiskit/pulse/utils.py | 5 ++-- qiskit/qpy/interface.py | 2 +- qiskit/scheduler/utils.py | 10 +++---- qiskit/transpiler/passes/basis/decompose.py | 2 +- qiskit/utils/deprecation.py | 26 ++++++++++++++----- qiskit/visualization/state_visualization.py | 10 +++---- test/python/utils/test_deprecation.py | 4 +-- 26 files changed, 75 insertions(+), 59 deletions(-) diff --git a/qiskit/algorithms/aux_ops_evaluator.py b/qiskit/algorithms/aux_ops_evaluator.py index 9ce9349a7de8..9d395d81e702 100644 --- a/qiskit/algorithms/aux_ops_evaluator.py +++ b/qiskit/algorithms/aux_ops_evaluator.py @@ -37,6 +37,7 @@ "This function will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def eval_observables( quantum_instance: Union[QuantumInstance, Backend], diff --git a/qiskit/algorithms/evolvers/evolution_problem.py b/qiskit/algorithms/evolvers/evolution_problem.py index cd34c5a34f8a..9f38c7d52973 100644 --- a/qiskit/algorithms/evolvers/evolution_problem.py +++ b/qiskit/algorithms/evolvers/evolution_problem.py @@ -39,6 +39,7 @@ class EvolutionProblem: "This class will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def __init__( self, diff --git a/qiskit/algorithms/factorizers/shor.py b/qiskit/algorithms/factorizers/shor.py index 92872a3eabaa..3b79f5554aa7 100644 --- a/qiskit/algorithms/factorizers/shor.py +++ b/qiskit/algorithms/factorizers/shor.py @@ -61,7 +61,7 @@ class Shor: no sooner than 3 months after the release date. It is replaced by the tutorial at https://qiskit.org/textbook/ch-algorithms/shor.html """, - docstring_version="0.22.0", + since="0.22.0", ) def __init__(self, quantum_instance: Optional[Union[QuantumInstance, Backend]] = None) -> None: """ diff --git a/qiskit/algorithms/linear_solvers/hhl.py b/qiskit/algorithms/linear_solvers/hhl.py index 86e95cb4920c..d623be91e6da 100644 --- a/qiskit/algorithms/linear_solvers/hhl.py +++ b/qiskit/algorithms/linear_solvers/hhl.py @@ -113,7 +113,7 @@ class HHL(LinearSolver): no sooner than 3 months after the release date. It is replaced by the tutorial at https://qiskit.org/textbook/ch-applications/hhl_tutorial.html" """, - docstring_version="0.22.0", + since="0.22.0", ) def __init__( self, diff --git a/qiskit/algorithms/linear_solvers/linear_solver.py b/qiskit/algorithms/linear_solvers/linear_solver.py index 743bce2ddace..11d604c859c6 100644 --- a/qiskit/algorithms/linear_solvers/linear_solver.py +++ b/qiskit/algorithms/linear_solvers/linear_solver.py @@ -35,7 +35,7 @@ class LinearSolverResult(AlgorithmResult): @deprecate_function( "The LinearSolverResult class is deprecated as of Qiskit Terra 0.22.0 " "and will be removed no sooner than 3 months after the release date. ", - docstring_version="0.22.0", + since="0.22.0", ) def __init__(self) -> None: super().__init__() @@ -104,7 +104,7 @@ class LinearSolver(ABC): @deprecate_function( "The LinearSolver class is deprecated as of Qiskit Terra 0.22.0 " "and will be removed no sooner than 3 months after the release date. ", - docstring_version="0.22.0", + since="0.22.0", ) def __init__(self) -> None: pass diff --git a/qiskit/algorithms/linear_solvers/matrices/linear_system_matrix.py b/qiskit/algorithms/linear_solvers/matrices/linear_system_matrix.py index c295faffba11..69263e963450 100644 --- a/qiskit/algorithms/linear_solvers/matrices/linear_system_matrix.py +++ b/qiskit/algorithms/linear_solvers/matrices/linear_system_matrix.py @@ -26,7 +26,7 @@ class LinearSystemMatrix(BlueprintCircuit, ABC): @deprecate_function( "The LinearSystemMatrix class is deprecated as of Qiskit Terra 0.22.0 " "and will be removed no sooner than 3 months after the release date. ", - docstring_version="0.22.0", + since="0.22.0", ) def __init__( self, diff --git a/qiskit/algorithms/linear_solvers/matrices/numpy_matrix.py b/qiskit/algorithms/linear_solvers/matrices/numpy_matrix.py index 21edf50850f1..fc249faed04a 100644 --- a/qiskit/algorithms/linear_solvers/matrices/numpy_matrix.py +++ b/qiskit/algorithms/linear_solvers/matrices/numpy_matrix.py @@ -51,7 +51,7 @@ class NumPyMatrix(LinearSystemMatrix): @deprecate_function( "The NumPyMatrix class is deprecated as of Qiskit Terra 0.22.0 " "and will be removed no sooner than 3 months after the release date. ", - docstring_version="0.22.0", + since="0.22.0", ) def __init__( self, diff --git a/qiskit/algorithms/linear_solvers/matrices/tridiagonal_toeplitz.py b/qiskit/algorithms/linear_solvers/matrices/tridiagonal_toeplitz.py index a1027f432b7b..0b5879a74dd6 100644 --- a/qiskit/algorithms/linear_solvers/matrices/tridiagonal_toeplitz.py +++ b/qiskit/algorithms/linear_solvers/matrices/tridiagonal_toeplitz.py @@ -63,7 +63,7 @@ class TridiagonalToeplitz(LinearSystemMatrix): @deprecate_function( "The TridiagonalToeplitz class is deprecated as of Qiskit Terra 0.22.0 " "and will be removed no sooner than 3 months after the release date. ", - docstring_version="0.22.0", + since="0.22.0", ) def __init__( self, diff --git a/qiskit/algorithms/linear_solvers/numpy_linear_solver.py b/qiskit/algorithms/linear_solvers/numpy_linear_solver.py index bafcfe5133a5..1359074d86a0 100644 --- a/qiskit/algorithms/linear_solvers/numpy_linear_solver.py +++ b/qiskit/algorithms/linear_solvers/numpy_linear_solver.py @@ -56,7 +56,7 @@ class NumPyLinearSolver(LinearSolver): @deprecate_function( "The NumPyLinearSolver class is deprecated as of Qiskit Terra 0.22.0 " "and will be removed no sooner than 3 months after the release date. ", - docstring_version="0.22.0", + since="0.22.0", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/algorithms/linear_solvers/observables/absolute_average.py b/qiskit/algorithms/linear_solvers/observables/absolute_average.py index 994260e1afe7..88940ea70b7c 100644 --- a/qiskit/algorithms/linear_solvers/observables/absolute_average.py +++ b/qiskit/algorithms/linear_solvers/observables/absolute_average.py @@ -66,7 +66,7 @@ class AbsoluteAverage(LinearSystemObservable): @deprecate_function( "The AbsoluteAverage class is deprecated as of Qiskit Terra 0.22.0 " "and will be removed no sooner than 3 months after the release date. ", - docstring_version="0.22.0", + since="0.22.0", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/algorithms/linear_solvers/observables/linear_system_observable.py b/qiskit/algorithms/linear_solvers/observables/linear_system_observable.py index e55227de4538..7beb7c18cb20 100644 --- a/qiskit/algorithms/linear_solvers/observables/linear_system_observable.py +++ b/qiskit/algorithms/linear_solvers/observables/linear_system_observable.py @@ -27,7 +27,7 @@ class LinearSystemObservable(ABC): @deprecate_function( "The LinearSystemObservable class is deprecated as of Qiskit Terra 0.22.0 " "and will be removed no sooner than 3 months after the release date. ", - docstring_version="0.22.0", + since="0.22.0", ) def __init__(self) -> None: pass diff --git a/qiskit/algorithms/linear_solvers/observables/matrix_functional.py b/qiskit/algorithms/linear_solvers/observables/matrix_functional.py index 250282f49369..195982a2c94b 100644 --- a/qiskit/algorithms/linear_solvers/observables/matrix_functional.py +++ b/qiskit/algorithms/linear_solvers/observables/matrix_functional.py @@ -78,7 +78,7 @@ class MatrixFunctional(LinearSystemObservable): @deprecate_function( "The MatrixFunctional class is deprecated as of Qiskit Terra 0.22.0 " "and will be removed no sooner than 3 months after the release date. ", - docstring_version="0.22.0", + since="0.22.0", ) def __init__(self, main_diag: float, off_diag: int) -> None: """ diff --git a/qiskit/algorithms/optimizers/adam_amsgrad.py b/qiskit/algorithms/optimizers/adam_amsgrad.py index 626b43f8fdd5..c1c9a64bdbc8 100644 --- a/qiskit/algorithms/optimizers/adam_amsgrad.py +++ b/qiskit/algorithms/optimizers/adam_amsgrad.py @@ -199,7 +199,7 @@ def load_params(self, load_dir: str) -> None: "initial_point": "x0", "gradient_function": "jac", }, - docstring_version="0.19.0", + since="0.19.0", ) # pylint: disable=arguments-differ def minimize( diff --git a/qiskit/algorithms/optimizers/spsa.py b/qiskit/algorithms/optimizers/spsa.py index d4cccf813d56..b81a360c813e 100644 --- a/qiskit/algorithms/optimizers/spsa.py +++ b/qiskit/algorithms/optimizers/spsa.py @@ -652,7 +652,7 @@ def get_support_level(self): "sooner than 3 months after the release date. Instead, use SPSA.minimize as a replacement, " "which supports the same arguments but follows the interface of scipy.optimize and returns " "a complete result object containing additional information.", - docstring_version="0.21.0", + since="0.21.0", ) def optimize( self, diff --git a/qiskit/algorithms/phase_estimators/phase_estimation_result.py b/qiskit/algorithms/phase_estimators/phase_estimation_result.py index ffc114d66a13..b4cb2ab236f8 100644 --- a/qiskit/algorithms/phase_estimators/phase_estimation_result.py +++ b/qiskit/algorithms/phase_estimators/phase_estimation_result.py @@ -72,7 +72,7 @@ def circuit_result(self) -> Result: """The 'PhaseEstimationResult.most_likely_phase' attribute is deprecated as of 0.18.0 and will be removed no earlier than 3 months after the release date. It has been renamed as the 'phase' attribute.""", - docstring_version="0.18.0", + since="0.18.0", ) def most_likely_phase(self) -> float: r"""DEPRECATED - Return the most likely phase as a number in :math:`[0.0, 1.0)`. diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py index 28e278d16d4a..e167c67a22d9 100644 --- a/qiskit/circuit/quantumcircuit.py +++ b/qiskit/circuit/quantumcircuit.py @@ -717,7 +717,7 @@ def control( "The QuantumCircuit.combine() method is being deprecated. " "Use the compose() method which is more flexible w.r.t " "circuit register compatibility.", - docstring_version="0.17.0", + since="0.17.0", ) def combine(self, rhs: "QuantumCircuit") -> "QuantumCircuit": """Returns rhs appended to self if self contains compatible registers. @@ -770,7 +770,7 @@ def combine(self, rhs: "QuantumCircuit") -> "QuantumCircuit": "The QuantumCircuit.extend() method is being deprecated. Use the " "compose() (potentially with the inplace=True argument) and tensor() " "methods which are more flexible w.r.t circuit register compatibility.", - docstring_version="0.17.0", + since="0.17.0", ) def extend(self, rhs: "QuantumCircuit") -> "QuantumCircuit": """DEPRECATED - Append QuantumCircuit to the RHS if it contains compatible registers. @@ -1111,7 +1111,8 @@ def ancillas(self) -> List[AncillaQubit]: @deprecate_function( "The QuantumCircuit.__add__() method is being deprecated." "Use the compose() method which is more flexible w.r.t " - "circuit register compatibility." + "circuit register compatibility.", + modify_docstring=False, ) def __add__(self, rhs: "QuantumCircuit") -> "QuantumCircuit": """Overload + to implement self.combine.""" @@ -1120,7 +1121,8 @@ def __add__(self, rhs: "QuantumCircuit") -> "QuantumCircuit": @deprecate_function( "The QuantumCircuit.__iadd__() method is being deprecated. Use the " "compose() (potentially with the inplace=True argument) and tensor() " - "methods which are more flexible w.r.t circuit register compatibility." + "methods which are more flexible w.r.t circuit register compatibility.", + modify_docstring=False, ) def __iadd__(self, rhs: "QuantumCircuit") -> "QuantumCircuit": """Overload += to implement self.extend.""" @@ -3768,7 +3770,7 @@ def cu( "after the release date. You should use the " "QuantumCircuit.p method instead, which acts " "identically.", - docstring_version="0.16.0", + since="0.16.0", ) def u1(self, theta: ParameterValueType, qubit: QubitSpecifier) -> InstructionSet: r"""Apply :class:`~qiskit.circuit.library.U1Gate`. @@ -3792,7 +3794,7 @@ def u1(self, theta: ParameterValueType, qubit: QubitSpecifier) -> InstructionSet "after the release date. You should use the " "QuantumCircuit.cp method instead, which acts " "identically.", - docstring_version="0.16.0", + since="0.16.0", ) def cu1( self, @@ -3830,7 +3832,7 @@ def cu1( "after the release date. You should use the " "QuantumCircuit.mcp method instead, which acts " "identically.", - docstring_version="0.16.0", + since="0.16.0", ) def mcu1( self, @@ -3863,7 +3865,7 @@ def mcu1( "u(π/2, φ, λ). Alternatively, you can decompose it in" "terms of QuantumCircuit.p and QuantumCircuit.sx: " "u2(φ,λ) = p(π/2+φ) sx p(λ-π/2) (1 pulse on hardware).", - docstring_version="0.16.0", + since="0.16.0", ) def u2( self, phi: ParameterValueType, lam: ParameterValueType, qubit: QubitSpecifier @@ -3890,7 +3892,7 @@ def u2( "QuantumCircuit.u instead, which acts identically. Alternatively, you can " "decompose u3 in terms of QuantumCircuit.p and QuantumCircuit.sx: " "u3(ϴ,φ,λ) = p(φ+π) sx p(ϴ+π) sx p(λ) (2 pulses on hardware).", - docstring_version="0.16.0", + since="0.16.0", ) def u3( self, @@ -3921,7 +3923,7 @@ def u3( "removed no earlier than 3 months after the release date. You should " "use the QuantumCircuit.cu method instead, where " "cu3(ϴ,φ,λ) = cu(ϴ,φ,λ,0).", - docstring_version="0.16.0", + since="0.16.0", ) def cu3( self, diff --git a/qiskit/dagcircuit/dagcircuit.py b/qiskit/dagcircuit/dagcircuit.py index 736ff3c356a1..093a99c52377 100644 --- a/qiskit/dagcircuit/dagcircuit.py +++ b/qiskit/dagcircuit/dagcircuit.py @@ -98,7 +98,7 @@ def __init__(self): @_optionals.HAS_NETWORKX.require_in_call @deprecate_function( "The to_networkx() method is deprecated and will be removed in a future release.", - docstring_version="0.21.0", + since="0.21.0", ) def to_networkx(self): """Returns a copy of the DAGCircuit in networkx format.""" @@ -116,7 +116,7 @@ def to_networkx(self): @_optionals.HAS_NETWORKX.require_in_call @deprecate_function( "The from_networkx() method is deprecated and will be removed in a future release.", - docstring_version="0.21.0", + since="0.21.0", ) def from_networkx(cls, graph): """Take a networkx MultiDigraph and create a new DAGCircuit. @@ -506,7 +506,7 @@ def _add_op_node(self, op, qargs, cargs): no earlier than 3 months after the release date. You should use the DAGCircuit.copy_empty_like method instead, which acts identically. """, - docstring_version="0.20.0", + since="0.20.0", ) def _copy_circuit_metadata(self): """DEPRECATED""" diff --git a/qiskit/primitives/base_estimator.py b/qiskit/primitives/base_estimator.py index ae9da9009770..eecbd0bd9080 100644 --- a/qiskit/primitives/base_estimator.py +++ b/qiskit/primitives/base_estimator.py @@ -215,7 +215,7 @@ def __new__( "The BaseEstimator.__enter__ method is deprecated as of Qiskit Terra 0.22.0 " "and will be removed no sooner than 3 months after the release date. " "BaseEstimator should be initialized directly.", - docstring_version="0.22.0", + since="0.22.0", ) def __enter__(self): return self @@ -224,7 +224,7 @@ def __enter__(self): "The BaseEstimator.__exit__ method is deprecated as of Qiskit Terra 0.22.0 " "and will be removed no sooner than 3 months after the release date. " "BaseEstimator should be initialized directly.", - docstring_version="0.22.0", + since="0.22.0", ) def __exit__(self, *exc_info): self.close() @@ -281,11 +281,10 @@ def set_options(self, **fields) -> BaseEstimator: "The BaseSampler.__call__ method is deprecated as of Qiskit Terra 0.22.0 " "and will be removed no sooner than 3 months after the release date. " "Use run method instead.", - docstring_version="0.22.0", + since="0.22.0", ) @deprecate_arguments( - {"circuit_indices": "circuits", "observable_indices": "observables"}, - docstring_version="0.21.0", + {"circuit_indices": "circuits", "observable_indices": "observables"}, since="0.21.0" ) def __call__( self, diff --git a/qiskit/primitives/base_sampler.py b/qiskit/primitives/base_sampler.py index de2894d4ea8e..3391def5c13f 100644 --- a/qiskit/primitives/base_sampler.py +++ b/qiskit/primitives/base_sampler.py @@ -176,7 +176,7 @@ def __new__( @deprecate_function( "The BaseSampler.__enter__ method is deprecated as of Qiskit Terra 0.22.0 " "and will be removed no sooner than 3 months after the release date. " - "BaseSampler should be initialized directly.", + "BaseSampler should be initialized directly." ) def __enter__(self): return self @@ -184,7 +184,7 @@ def __enter__(self): @deprecate_function( "The BaseSampler.__exit__ method is deprecated as of Qiskit Terra 0.22.0 " "and will be removed no sooner than 3 months after the release date. " - "BaseSampler should be initialized directly.", + "BaseSampler should be initialized directly." ) def __exit__(self, *exc_info): self.close() @@ -231,9 +231,9 @@ def set_options(self, **fields): @deprecate_function( "The BaseSampler.__call__ method is deprecated as of Qiskit Terra 0.22.0 " "and will be removed no sooner than 3 months after the release date. " - "Use run method instead.", + "Use run method instead." ) - @deprecate_arguments({"circuit_indices": "circuits"}, docstring_version="0.21.0") + @deprecate_arguments({"circuit_indices": "circuits"}, since="0.21.0") def __call__( self, circuits: Sequence[int | QuantumCircuit], diff --git a/qiskit/pulse/utils.py b/qiskit/pulse/utils.py index c5f77749e4ed..9756dc5cece8 100644 --- a/qiskit/pulse/utils.py +++ b/qiskit/pulse/utils.py @@ -98,7 +98,7 @@ def instruction_duration_validation(duration: int): ) -@deprecate_function("Deprecated since Terra 0.22.0. Use 'qiskit.utils.deprecate_function' instead.") +@deprecate_function("Use 'qiskit.utils.deprecate_function' instead.", since="0.22.0") def deprecated_functionality(func): """A decorator that raises deprecation warning without showing alternative method.""" return deprecate_function( @@ -106,6 +106,7 @@ def deprecated_functionality(func): "No alternative method will be provided with this change. " "If there is any practical usage of this functionality, please write " "an issue in Qiskit/qiskit-terra repository.", - category=DeprecationWarning, stacklevel=2, + category=DeprecationWarning, + modify_docstring=False, )(func) diff --git a/qiskit/qpy/interface.py b/qiskit/qpy/interface.py index 7af31678701a..d33de723cd21 100644 --- a/qiskit/qpy/interface.py +++ b/qiskit/qpy/interface.py @@ -72,7 +72,7 @@ VERSION_PATTERN_REGEX = re.compile(VERSION_PATTERN, re.VERBOSE | re.IGNORECASE) -@deprecate_arguments({"circuits": "programs"}, docstring_version="0.21.0") +@deprecate_arguments({"circuits": "programs"}, since="0.21.0") def dump( programs: Union[List[QPY_SUPPORTED_TYPES], QPY_SUPPORTED_TYPES], file_obj: BinaryIO, diff --git a/qiskit/scheduler/utils.py b/qiskit/scheduler/utils.py index a0a085070315..ee1cc014ae49 100644 --- a/qiskit/scheduler/utils.py +++ b/qiskit/scheduler/utils.py @@ -16,13 +16,13 @@ from qiskit.pulse import macros, utils format_meas_map = deprecate_function( - '"format_meas_map" has been moved to "qiskit.pulse.utils"', docstring_version="0.15.0" + '"format_meas_map" has been moved to "qiskit.pulse.utils"', since="0.15.0" )(utils.format_meas_map) -measure = deprecate_function( - '"measure" has been moved to "qiskit.pulse.macros"', docstring_version="0.15.0" -)(macros.measure) +measure = deprecate_function('"measure" has been moved to "qiskit.pulse.macros"', since="0.15.0")( + macros.measure +) measure_all = deprecate_function( - '"measure_all" has been moved to "qiskit.pulse.macros"', docstring_version="0.15.0" + '"measure_all" has been moved to "qiskit.pulse.macros"', since="0.15.0" )(macros.measure_all) diff --git a/qiskit/transpiler/passes/basis/decompose.py b/qiskit/transpiler/passes/basis/decompose.py index 6f4d23f7684f..0073f043b4b6 100644 --- a/qiskit/transpiler/passes/basis/decompose.py +++ b/qiskit/transpiler/passes/basis/decompose.py @@ -25,7 +25,7 @@ class Decompose(TransformationPass): """Expand a gate in a circuit using its decomposition rules.""" - @deprecate_arguments({"gate": "gates_to_decompose"}, docstring_version="0.19.0") + @deprecate_arguments({"gate": "gates_to_decompose"}, since="0.19.0") def __init__( self, gate: Optional[Type[Gate]] = None, diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index de5a56b5b8ae..90a3dfd4fb2d 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -16,15 +16,21 @@ import warnings from typing import Type +from qiskit.exceptions import QiskitError + def deprecate_arguments( - kwarg_map, category: Type[Warning] = DeprecationWarning, docstring_version=None + kwarg_map, category: Type[Warning] = DeprecationWarning, modify_docstring=True, since=None ): """Decorator to automatically alias deprecated argument names and warn upon use.""" def decorator(func): - if docstring_version and kwarg_map: - func.__doc__ = "\n".join(_extend_docstring(func, docstring_version, kwarg_map)) + if modify_docstring and since is None: + raise QiskitError( + "Modifying the docstring needs a version. Add parameter `since` with it." + ) + if modify_docstring and since and kwarg_map: + func.__doc__ = "\n".join(_extend_docstring(func, since, kwarg_map)) @functools.wraps(func) def wrapper(*args, **kwargs): @@ -41,7 +47,8 @@ def deprecate_function( msg: str, stacklevel: int = 2, category: Type[Warning] = DeprecationWarning, - docstring_version: str = None, + modify_docstring=True, + since: str = None, ): """Emit a warning prior to calling decorated function. @@ -49,7 +56,7 @@ def deprecate_function( msg: Warning message to emit. stacklevel: The warning stackevel to use, defaults to 2. category: warning category, defaults to DeprecationWarning - docstring_version (str): If a version number, extends the docstring with a deprecation warning + since (str): If a version number, extends the docstring with a deprecation warning box. If `None`, no docstring box will be added. Default: None Returns: @@ -57,9 +64,14 @@ def deprecate_function( """ def decorator(func): - if docstring_version: + if modify_docstring and since is None: + raise QiskitError( + "Modifying the docstring needs a version. Add parameter `since` with it." + ) + + if modify_docstring and since: func.__doc__ = "\n".join( - _extend_docstring(func, docstring_version, {None: msg.expandtabs().splitlines()}) + _extend_docstring(func, since, {None: msg.expandtabs().splitlines()}) ) @functools.wraps(func) diff --git a/qiskit/visualization/state_visualization.py b/qiskit/visualization/state_visualization.py index 7f9189774990..cc3d8f10d34a 100644 --- a/qiskit/visualization/state_visualization.py +++ b/qiskit/visualization/state_visualization.py @@ -34,7 +34,7 @@ from .exceptions import VisualizationError -@deprecate_arguments({"rho": "state"}, docstring_version="0.15.1") +@deprecate_arguments({"rho": "state"}, since="0.15.1") @_optionals.HAS_MATPLOTLIB.require_in_call def plot_state_hinton( state, title="", figsize=None, ax_real=None, ax_imag=None, *, rho=None, filename=None @@ -241,7 +241,7 @@ def plot_bloch_vector(bloch, title="", ax=None, figsize=None, coord_type="cartes return None -@deprecate_arguments({"rho": "state"}, docstring_version="0.15.1") +@deprecate_arguments({"rho": "state"}, since="0.15.1") @_optionals.HAS_MATPLOTLIB.require_in_call def plot_bloch_multivector( state, title="", figsize=None, *, rho=None, reverse_bits=False, filename=None @@ -319,7 +319,7 @@ def plot_bloch_multivector( return fig.savefig(filename) -@deprecate_arguments({"rho": "state"}, docstring_version="0.15.1") +@deprecate_arguments({"rho": "state"}, since="0.15.1") @_optionals.HAS_MATPLOTLIB.require_in_call def plot_state_city( state, @@ -567,7 +567,7 @@ def plot_state_city( return fig.savefig(filename) -@deprecate_arguments({"rho": "state"}, docstring_version="0.15.1") +@deprecate_arguments({"rho": "state"}, since="0.15.1") @_optionals.HAS_MATPLOTLIB.require_in_call def plot_state_paulivec( state, title="", figsize=None, color=None, ax=None, *, rho=None, filename=None @@ -725,7 +725,7 @@ def phase_to_rgb(complex_number): return rgb -@deprecate_arguments({"rho": "state"}, docstring_version="0.15.1") +@deprecate_arguments({"rho": "state"}, since="0.15.1") @_optionals.HAS_MATPLOTLIB.require_in_call @_optionals.HAS_SEABORN.require_in_call def plot_state_qsphere( diff --git a/test/python/utils/test_deprecation.py b/test/python/utils/test_deprecation.py index e3a5b7b4f326..d7d9b81b293d 100644 --- a/test/python/utils/test_deprecation.py +++ b/test/python/utils/test_deprecation.py @@ -28,7 +28,7 @@ def __init__(self, arg1: int = None, arg2: [int] = None): @deprecate_function( "The DummyClass.foo() method is being deprecated. Use the DummyClass.some_othermethod()", - docstring_version="1.2.3", + since="1.2.3", ) def foo_deprecated(self, index_arg2: int): """A multi-line @@ -49,7 +49,7 @@ def foo_deprecated(self, index_arg2: int): raise QiskitError("there is an error") return self.arg2[index_arg2] - @deprecate_arguments({"if_arg1": "other_if_arg1"}, docstring_version="1.2.3") + @deprecate_arguments({"if_arg1": "other_if_arg1"}, since="1.2.3") def bar_with_deprecated_arg( self, if_arg1: int = None, index_arg2: int = None, other_if_arg1: int = None ): From ab7277ab6fcfff2681007b95a96034ed3f9c4444 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 22 Sep 2022 15:04:16 +0200 Subject: [PATCH 14/36] docstring --- qiskit/utils/deprecation.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index 90a3dfd4fb2d..60530ce65a84 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -56,8 +56,9 @@ def deprecate_function( msg: Warning message to emit. stacklevel: The warning stackevel to use, defaults to 2. category: warning category, defaults to DeprecationWarning - since (str): If a version number, extends the docstring with a deprecation warning - box. If `None`, no docstring box will be added. Default: None + modify_docstring: docstring box will be added. Default: True + since: If a version number, extends the docstring with a deprecation warning + box. If `modify_docstring == True`, then mandatory Returns: Callable: The decorated, deprecated callable. From e5feaf8552042b1853e696b3c8adc54ebbaec71f Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 22 Sep 2022 15:12:27 +0200 Subject: [PATCH 15/36] split tests --- test/python/utils/test_deprecation.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/test/python/utils/test_deprecation.py b/test/python/utils/test_deprecation.py index d7d9b81b293d..e52447a1b973 100644 --- a/test/python/utils/test_deprecation.py +++ b/test/python/utils/test_deprecation.py @@ -73,8 +73,8 @@ def bar_with_deprecated_arg( return None -class TestDeprecation(QiskitTestCase): - """Test deprecation decorators.""" +class TestDeprecationRaise(QiskitTestCase): + """Test deprecation decorators raise warning.""" def assertDeprecationWarning(self, warn, expected_msg): """Checks there only one exception and `expected_msg` is the message""" @@ -107,7 +107,11 @@ def test_raise_deprecate_arguments(self): ) self.assertEqual(output, 1) - def test_docstring_deprecate_function(self): + +class TestDeprecationDocstring(QiskitTestCase): + """Test deprecation decorators docstring modification for DummyClass.""" + + def test_dummyclass_deprecate_function(self): """Test deprecate_function docstring.""" dummy = DummyClass() @@ -131,8 +135,8 @@ def test_docstring_deprecate_function(self): """ self.assertEqual(deprecated_docstring, expected) - def test_docstring_deprecate_arguments(self): - """Test deprecate_arguments docstring.""" + def test_dummayclass_deprecate_arguments(self): + """Test deprecate_arguments docstring for DummyClass.""" dummy = DummyClass() deprecated_docstring = dummy.bar_with_deprecated_arg.__doc__ From 427a3347f3c52591ad8a2dcc4105c427b1a12a0d Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 28 Sep 2022 21:53:51 +0200 Subject: [PATCH 16/36] raise warning instead of exception --- qiskit/utils/deprecation.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index 60530ce65a84..7cb951552070 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -16,8 +16,6 @@ import warnings from typing import Type -from qiskit.exceptions import QiskitError - def deprecate_arguments( kwarg_map, category: Type[Warning] = DeprecationWarning, modify_docstring=True, since=None @@ -26,8 +24,9 @@ def deprecate_arguments( def decorator(func): if modify_docstring and since is None: - raise QiskitError( - "Modifying the docstring needs a version. Add parameter `since` with it." + warnings.warn( + "Modifying the docstring needs a version. Add parameter `since` with it.", + stacklevel=2, ) if modify_docstring and since and kwarg_map: func.__doc__ = "\n".join(_extend_docstring(func, since, kwarg_map)) @@ -47,7 +46,7 @@ def deprecate_function( msg: str, stacklevel: int = 2, category: Type[Warning] = DeprecationWarning, - modify_docstring=True, + modify_docstring: bool = True, since: str = None, ): """Emit a warning prior to calling decorated function. @@ -66,8 +65,9 @@ def deprecate_function( def decorator(func): if modify_docstring and since is None: - raise QiskitError( - "Modifying the docstring needs a version. Add parameter `since` with it." + warnings.warn( + "Modifying the docstring needs a version. Add parameter `since` with it.", + stacklevel=2, ) if modify_docstring and since: From c9d4e38888de7555e0a303e4cd243d304676b993 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Oct 2022 10:55:31 +0200 Subject: [PATCH 17/36] lint --- qiskit/primitives/base/base_estimator.py | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/qiskit/primitives/base/base_estimator.py b/qiskit/primitives/base/base_estimator.py index b997d9db9146..d606ebfbfb17 100644 --- a/qiskit/primitives/base/base_estimator.py +++ b/qiskit/primitives/base/base_estimator.py @@ -94,7 +94,7 @@ from qiskit.providers import JobV1 as Job from qiskit.quantum_info.operators import SparsePauliOp from qiskit.quantum_info.operators.base_operator import BaseOperator -from qiskit.utils.deprecation import deprecate_arguments, deprecate_function +from qiskit.utils.deprecation import deprecate_function from .base_primitive import BasePrimitive from .estimator_result import EstimatorResult @@ -366,17 +366,9 @@ def parameters(self) -> tuple[ParameterView, ...]: return tuple(self._parameters) @deprecate_function( - "The BaseEstimator.__enter__ method is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the releasedate. " - "BaseEstimator should be initialized directly.", - ) - def __enter__(self): - return self - - @deprecate_function( - "The BaseEstimator.__call__ method is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the releasedate. " - "Use the 'run' method instead.", + """The BaseEstimator.__call__ method is deprecated as of Qiskit Terra 0.22.0 + and will be removed no sooner than 3 months after the release date. + Use the 'run' method instead.""" ) def __call__( self, From a7f0e0bf4ad4705c5d99e8b7fb5794f3eecd913a Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Oct 2022 11:06:09 +0200 Subject: [PATCH 18/36] base_estimator --- qiskit/primitives/base/base_estimator.py | 12 ------------ qiskit/quantum_info/operators/symplectic/random.py | 7 ++++--- 2 files changed, 4 insertions(+), 15 deletions(-) diff --git a/qiskit/primitives/base/base_estimator.py b/qiskit/primitives/base/base_estimator.py index d606ebfbfb17..cde6ef1dfb55 100644 --- a/qiskit/primitives/base/base_estimator.py +++ b/qiskit/primitives/base/base_estimator.py @@ -316,21 +316,9 @@ def __new__( self._observable_ids = {_observable_key(init_observable(observables)): 0} return self - @deprecate_function( - "The BaseEstimator.__enter__ method is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the release date. " - "BaseEstimator should be initialized directly.", - since="0.22.0", - ) def __enter__(self): return self - @deprecate_function( - "The BaseEstimator.__exit__ method is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the release date. " - "BaseEstimator should be initialized directly.", - since="0.22.0", - ) def __exit__(self, *exc_info): self.close() diff --git a/qiskit/quantum_info/operators/symplectic/random.py b/qiskit/quantum_info/operators/symplectic/random.py index 4cea74684e25..2fa8f7ebeb6e 100644 --- a/qiskit/quantum_info/operators/symplectic/random.py +++ b/qiskit/quantum_info/operators/symplectic/random.py @@ -104,9 +104,10 @@ def random_pauli_table(num_qubits, size=1, seed=None): @deprecate_function( - "The random_stabilizer_table function is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the release date. " - "Use random_pauli_list method instead." # pylint: disable=bad-docstring-quotes + """The random_stabilizer_table function is deprecated as of Qiskit Terra 0.22.0 + and will be removed no sooner than 3 months after the release date. + Use random_pauli_list method instead.""", + since="0.22.0", ) def random_stabilizer_table(num_qubits, size=1, seed=None): """DEPRECATED: Return a random StabilizerTable. From bdf623e87931a6cd891cd5efec8b6112477d67cb Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Oct 2022 11:15:31 +0200 Subject: [PATCH 19/36] more merging conflicts --- qiskit/primitives/base/base_estimator.py | 40 +++++++++++++++--------- qiskit/primitives/base/base_sampler.py | 16 +++++----- 2 files changed, 33 insertions(+), 23 deletions(-) diff --git a/qiskit/primitives/base/base_estimator.py b/qiskit/primitives/base/base_estimator.py index cde6ef1dfb55..eeb815e369c2 100644 --- a/qiskit/primitives/base/base_estimator.py +++ b/qiskit/primitives/base/base_estimator.py @@ -94,7 +94,7 @@ from qiskit.providers import JobV1 as Job from qiskit.quantum_info.operators import SparsePauliOp from qiskit.quantum_info.operators.base_operator import BaseOperator -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_arguments, deprecate_function from .base_primitive import BasePrimitive from .estimator_result import EstimatorResult @@ -316,16 +316,6 @@ def __new__( self._observable_ids = {_observable_key(init_observable(observables)): 0} return self - def __enter__(self): - return self - - def __exit__(self, *exc_info): - self.close() - - def close(self): - """Close the session and free resources""" - ... - @property def circuits(self) -> tuple[QuantumCircuit, ...]: """Quantum circuits that represents quantum states. @@ -354,9 +344,31 @@ def parameters(self) -> tuple[ParameterView, ...]: return tuple(self._parameters) @deprecate_function( - """The BaseEstimator.__call__ method is deprecated as of Qiskit Terra 0.22.0 - and will be removed no sooner than 3 months after the release date. - Use the 'run' method instead.""" + "The BaseEstimator.__enter__ method is deprecated. " + "BaseEstimator should be initialized directly.", + since="0.22.0", + ) + def __enter__(self): + return self + + @deprecate_function( + "The BaseEstimator.__call__ method is deprecated. " + "BaseEstimator should be initialized directly.", + since="0.22.0", + ) + def __exit__(self, *exc_info): + self.close() + + def close(self): + """Close the session and free resources""" + ... + + @deprecate_function( + "The BaseEstimator.__call__ method is deprecated. " "Use the 'run' method instead.", + since="0.22.0", + ) + @deprecate_arguments( + {"circuit_indices": "circuits", "observable_indices": "observables"}, since="0.21.0" ) def __call__( self, diff --git a/qiskit/primitives/base/base_sampler.py b/qiskit/primitives/base/base_sampler.py index 5d9a2c91fc18..69dc933367c8 100644 --- a/qiskit/primitives/base/base_sampler.py +++ b/qiskit/primitives/base/base_sampler.py @@ -257,17 +257,17 @@ def parameters(self) -> tuple[ParameterView, ...]: return tuple(self._parameters) @deprecate_function( - "The BaseSampler.__enter__ method is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the release date. " - "BaseSampler should be initialized directly." + "The BaseSampler.__enter__ method is deprecated. " + "BaseSampler should be initialized directly.", + since="0.22.0", ) def __enter__(self): return self @deprecate_function( - "The BaseSampler.__exit__ method is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the release date. " - "BaseSampler should be initialized directly." + "The BaseSampler.__exit__ method is deprecated. " + "BaseSampler should be initialized directly.", + since="0.22.0", ) def __exit__(self, *exc_info): self.close() @@ -277,9 +277,7 @@ def close(self): ... @deprecate_function( - "The BaseSampler.__call__ method is deprecated as of Qiskit Terra 0.22.0 " - "and will be removed no sooner than 3 months after the release date. " - "Use run method instead." + "The BaseSampler.__call__ method is deprecated. " "Use run method instead.", since="0.22.0" ) @deprecate_arguments({"circuit_indices": "circuits"}, since="0.21.0") def __call__( From 82b9cc2cc06b116b442c09e4e37c233c1647efe3 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Oct 2022 11:55:55 +0200 Subject: [PATCH 20/36] turn into exception --- qiskit/utils/deprecation.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index 7cb951552070..28b57f3c4949 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -16,6 +16,8 @@ import warnings from typing import Type +from qiskit.exceptions import QiskitError + def deprecate_arguments( kwarg_map, category: Type[Warning] = DeprecationWarning, modify_docstring=True, since=None @@ -24,9 +26,9 @@ def deprecate_arguments( def decorator(func): if modify_docstring and since is None: - warnings.warn( - "Modifying the docstring needs a version. Add parameter `since` with it.", - stacklevel=2, + raise QiskitError( + "Adding a 'deprecated' directive to the docstring needs a version. " + "Add parameter `since` to `deprecate_arguments`." ) if modify_docstring and since and kwarg_map: func.__doc__ = "\n".join(_extend_docstring(func, since, kwarg_map)) @@ -53,7 +55,7 @@ def deprecate_function( Args: msg: Warning message to emit. - stacklevel: The warning stackevel to use, defaults to 2. + stacklevel: The warning stacklevel to use, defaults to 2. category: warning category, defaults to DeprecationWarning modify_docstring: docstring box will be added. Default: True since: If a version number, extends the docstring with a deprecation warning @@ -65,9 +67,9 @@ def deprecate_function( def decorator(func): if modify_docstring and since is None: - warnings.warn( - "Modifying the docstring needs a version. Add parameter `since` with it.", - stacklevel=2, + raise QiskitError( + "Adding a 'deprecated' directive to the docstring needs a version. " + "Add parameter `since` to `deprecate_arguments`." ) if modify_docstring and since: @@ -111,7 +113,7 @@ def _rename_kwargs(func_name, kwargs, kwarg_map, category: Type[Warning] = Depre def _extend_docstring(func, version, kwarg_map): """kwarg_map[None] means message in no kwarg, and it will be - append to the long desscription""" + appended to the long description""" docstr = func.__doc__ if docstr: docstr_lines = docstr.expandtabs().splitlines() From b32cfc52a1d56ce70449010b8eb026443769f352 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Oct 2022 15:08:20 +0200 Subject: [PATCH 21/36] back to warning --- .../algorithms/amplitude_amplifiers/grover.py | 2 ++ qiskit/algorithms/amplitude_estimators/ae.py | 2 ++ qiskit/algorithms/amplitude_estimators/fae.py | 2 ++ qiskit/algorithms/amplitude_estimators/iae.py | 2 ++ .../algorithms/amplitude_estimators/mlae.py | 2 ++ .../algorithms/eigen_solvers/eigen_solver.py | 2 ++ .../eigen_solvers/numpy_eigen_solver.py | 1 + qiskit/algorithms/eigen_solvers/vqd.py | 2 ++ .../algorithms/evolvers/evolution_result.py | 1 + .../algorithms/evolvers/imaginary_evolver.py | 1 + qiskit/algorithms/evolvers/real_evolver.py | 1 + .../evolvers/trotterization/trotter_qrte.py | 1 + .../minimum_eigen_solver.py | 2 ++ .../numpy_minimum_eigen_solver.py | 1 + .../algorithms/minimum_eigen_solvers/qaoa.py | 1 + .../algorithms/minimum_eigen_solvers/vqe.py | 2 ++ qiskit/utils/deprecation.py | 33 ++++++++++++------- 17 files changed, 46 insertions(+), 12 deletions(-) diff --git a/qiskit/algorithms/amplitude_amplifiers/grover.py b/qiskit/algorithms/amplitude_amplifiers/grover.py index 17dd9f00952a..c50bb5ec3fa1 100644 --- a/qiskit/algorithms/amplitude_amplifiers/grover.py +++ b/qiskit/algorithms/amplitude_amplifiers/grover.py @@ -195,6 +195,7 @@ def __init__( "This property will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def quantum_instance(self) -> Optional[QuantumInstance]: r"""Pending deprecation\; Get the quantum instance. @@ -210,6 +211,7 @@ def quantum_instance(self) -> Optional[QuantumInstance]: "This property will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def quantum_instance(self, quantum_instance: Union[QuantumInstance, Backend]) -> None: r"""Pending deprecation\; Set quantum instance. diff --git a/qiskit/algorithms/amplitude_estimators/ae.py b/qiskit/algorithms/amplitude_estimators/ae.py index 512405f19c9f..b939f00b7de5 100644 --- a/qiskit/algorithms/amplitude_estimators/ae.py +++ b/qiskit/algorithms/amplitude_estimators/ae.py @@ -129,6 +129,7 @@ def sampler(self, sampler: BaseSampler) -> None: "This property will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def quantum_instance(self) -> QuantumInstance | None: """Pending deprecation; Get the quantum instance. @@ -144,6 +145,7 @@ def quantum_instance(self) -> QuantumInstance | None: "This property will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def quantum_instance(self, quantum_instance: QuantumInstance | Backend) -> None: """Pending deprecation; Set quantum instance. diff --git a/qiskit/algorithms/amplitude_estimators/fae.py b/qiskit/algorithms/amplitude_estimators/fae.py index 697556840df0..a35b7de024e8 100644 --- a/qiskit/algorithms/amplitude_estimators/fae.py +++ b/qiskit/algorithms/amplitude_estimators/fae.py @@ -115,6 +115,7 @@ def sampler(self, sampler: BaseSampler) -> None: "This property will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def quantum_instance(self) -> QuantumInstance | None: """Pending deprecation; Get the quantum instance. @@ -130,6 +131,7 @@ def quantum_instance(self) -> QuantumInstance | None: "This property will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def quantum_instance(self, quantum_instance: QuantumInstance | Backend) -> None: """Pending deprecation; Set quantum instance. diff --git a/qiskit/algorithms/amplitude_estimators/iae.py b/qiskit/algorithms/amplitude_estimators/iae.py index 59a4429d0bf4..946f500fd1b2 100644 --- a/qiskit/algorithms/amplitude_estimators/iae.py +++ b/qiskit/algorithms/amplitude_estimators/iae.py @@ -138,6 +138,7 @@ def sampler(self, sampler: BaseSampler) -> None: "This property will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def quantum_instance(self) -> QuantumInstance | None: """Pending deprecation; Get the quantum instance. @@ -153,6 +154,7 @@ def quantum_instance(self) -> QuantumInstance | None: "This property will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def quantum_instance(self, quantum_instance: QuantumInstance | Backend) -> None: """Pending deprecation; Set quantum instance. diff --git a/qiskit/algorithms/amplitude_estimators/mlae.py b/qiskit/algorithms/amplitude_estimators/mlae.py index 8d46e1a2c21e..b6c8571cbab0 100644 --- a/qiskit/algorithms/amplitude_estimators/mlae.py +++ b/qiskit/algorithms/amplitude_estimators/mlae.py @@ -141,6 +141,7 @@ def sampler(self, sampler: BaseSampler) -> None: "This property will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def quantum_instance(self) -> QuantumInstance | None: """Pending deprecation; Get the quantum instance. @@ -156,6 +157,7 @@ def quantum_instance(self) -> QuantumInstance | None: "This property will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def quantum_instance(self, quantum_instance: QuantumInstance | Backend) -> None: """Pending deprecation; Set quantum instance. diff --git a/qiskit/algorithms/eigen_solvers/eigen_solver.py b/qiskit/algorithms/eigen_solvers/eigen_solver.py index a013b5c827cc..34103bf26ad3 100644 --- a/qiskit/algorithms/eigen_solvers/eigen_solver.py +++ b/qiskit/algorithms/eigen_solvers/eigen_solver.py @@ -42,6 +42,7 @@ class Eigensolver(ABC): "This interface will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def __init__(self) -> None: pass @@ -94,6 +95,7 @@ class EigensolverResult(AlgorithmResult): "This class will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py b/qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py index 77078dd6fbbc..781e1407f048 100755 --- a/qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py +++ b/qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py @@ -55,6 +55,7 @@ class NumPyEigensolver(Eigensolver): "This class will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def __init__( self, diff --git a/qiskit/algorithms/eigen_solvers/vqd.py b/qiskit/algorithms/eigen_solvers/vqd.py index d14ac038e1fe..399d0608fd4c 100644 --- a/qiskit/algorithms/eigen_solvers/vqd.py +++ b/qiskit/algorithms/eigen_solvers/vqd.py @@ -102,6 +102,7 @@ class VQD(VariationalAlgorithm, Eigensolver): "This class will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def __init__( self, @@ -772,6 +773,7 @@ class VQDResult(VariationalResult, EigensolverResult): "This class will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/algorithms/evolvers/evolution_result.py b/qiskit/algorithms/evolvers/evolution_result.py index 9ae567ca91c9..98239e906857 100644 --- a/qiskit/algorithms/evolvers/evolution_result.py +++ b/qiskit/algorithms/evolvers/evolution_result.py @@ -37,6 +37,7 @@ class EvolutionResult(AlgorithmResult): "This class will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def __init__( self, diff --git a/qiskit/algorithms/evolvers/imaginary_evolver.py b/qiskit/algorithms/evolvers/imaginary_evolver.py index 37a24d266a30..ee198598d485 100644 --- a/qiskit/algorithms/evolvers/imaginary_evolver.py +++ b/qiskit/algorithms/evolvers/imaginary_evolver.py @@ -35,6 +35,7 @@ class ImaginaryEvolver(ABC): "This interface will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def __init__(self) -> None: pass diff --git a/qiskit/algorithms/evolvers/real_evolver.py b/qiskit/algorithms/evolvers/real_evolver.py index c869344a19ba..e37689f536a3 100644 --- a/qiskit/algorithms/evolvers/real_evolver.py +++ b/qiskit/algorithms/evolvers/real_evolver.py @@ -35,6 +35,7 @@ class RealEvolver(ABC): "This interface will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def __init__(self) -> None: pass diff --git a/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py index e91793570d51..c5cebe9b1672 100644 --- a/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py +++ b/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py @@ -72,6 +72,7 @@ class TrotterQRTE(RealEvolver): "This class will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def __init__( self, diff --git a/qiskit/algorithms/minimum_eigen_solvers/minimum_eigen_solver.py b/qiskit/algorithms/minimum_eigen_solvers/minimum_eigen_solver.py index 373876a9e046..9535879f0861 100644 --- a/qiskit/algorithms/minimum_eigen_solvers/minimum_eigen_solver.py +++ b/qiskit/algorithms/minimum_eigen_solvers/minimum_eigen_solver.py @@ -42,6 +42,7 @@ class MinimumEigensolver(ABC): "This interface will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def __init__(self) -> None: pass @@ -98,6 +99,7 @@ class MinimumEigensolverResult(AlgorithmResult): "This class will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/algorithms/minimum_eigen_solvers/numpy_minimum_eigen_solver.py b/qiskit/algorithms/minimum_eigen_solvers/numpy_minimum_eigen_solver.py index 191a130a0163..dd2b9c1dc9e8 100644 --- a/qiskit/algorithms/minimum_eigen_solvers/numpy_minimum_eigen_solver.py +++ b/qiskit/algorithms/minimum_eigen_solvers/numpy_minimum_eigen_solver.py @@ -43,6 +43,7 @@ class NumPyMinimumEigensolver(MinimumEigensolver): "This class will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def __init__( self, diff --git a/qiskit/algorithms/minimum_eigen_solvers/qaoa.py b/qiskit/algorithms/minimum_eigen_solvers/qaoa.py index e650ee349cb1..5b9057ff9d29 100644 --- a/qiskit/algorithms/minimum_eigen_solvers/qaoa.py +++ b/qiskit/algorithms/minimum_eigen_solvers/qaoa.py @@ -65,6 +65,7 @@ class QAOA(VQE): "This class will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def __init__( self, diff --git a/qiskit/algorithms/minimum_eigen_solvers/vqe.py b/qiskit/algorithms/minimum_eigen_solvers/vqe.py index 286298620420..36315431c0ac 100755 --- a/qiskit/algorithms/minimum_eigen_solvers/vqe.py +++ b/qiskit/algorithms/minimum_eigen_solvers/vqe.py @@ -133,6 +133,7 @@ def my_minimizer(fun, x0, jac=None, bounds=None) -> OptimizerResult: "This class will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def __init__( self, @@ -672,6 +673,7 @@ class VQEResult(VariationalResult, MinimumEigensolverResult): "This class will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, + since="0.22.0", ) def __init__(self) -> None: with warnings.catch_warnings(): diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index 28b57f3c4949..392abd6faa10 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -16,8 +16,6 @@ import warnings from typing import Type -from qiskit.exceptions import QiskitError - def deprecate_arguments( kwarg_map, category: Type[Warning] = DeprecationWarning, modify_docstring=True, since=None @@ -26,12 +24,17 @@ def deprecate_arguments( def decorator(func): if modify_docstring and since is None: - raise QiskitError( - "Adding a 'deprecated' directive to the docstring needs a version. " - "Add parameter `since` to `deprecate_arguments`." + # TODO: replace with: raise QiskitError( + warnings.warn( + "Adding a 'deprecated' directive to the docstring needs a version. Add parameter `since`" + " to `deprecate_arguments` or disable docstring annotation with `modify_docstring=False`" + ". This warning will be a QiskitError exception in qiskit-terra 0.23.", + stacklevel=2, + category=FutureWarning, ) - if modify_docstring and since and kwarg_map: - func.__doc__ = "\n".join(_extend_docstring(func, since, kwarg_map)) + + if modify_docstring and kwarg_map: + func.__doc__ = "\n".join(_extend_docstring(func, since or "unknown_version", kwarg_map)) @functools.wraps(func) def wrapper(*args, **kwargs): @@ -67,14 +70,20 @@ def deprecate_function( def decorator(func): if modify_docstring and since is None: - raise QiskitError( - "Adding a 'deprecated' directive to the docstring needs a version. " - "Add parameter `since` to `deprecate_arguments`." + # TODO: replace with: raise QiskitError( + warnings.warn( + "Adding a 'deprecated' directive to the docstring needs a version. Add parameter `since`" + " to `deprecate_function` or disable docstring annotation with `modify_docstring=False`." + " This warning will be a QiskitError exception in qiskit-terra 0.23.", + stacklevel=2, + category=FutureWarning, ) - if modify_docstring and since: + if modify_docstring: func.__doc__ = "\n".join( - _extend_docstring(func, since, {None: msg.expandtabs().splitlines()}) + _extend_docstring( + func, since or "unknown_version", {None: msg.expandtabs().splitlines()} + ) ) @functools.wraps(func) From 033f49ff2283129a96e6af11cce1bcde7fbc20e9 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Oct 2022 21:52:15 +0200 Subject: [PATCH 22/36] warnings.filterwarnings() --- docs/conf.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/conf.py b/docs/conf.py index 443523cbccde..105166d7bc4d 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,6 +14,11 @@ """Sphinx documentation builder.""" +# TODO: remove this line, once Aer adapts to https://github.com/Qiskit/qiskit-terra/pull/8600 +import warnings + +warnings.filterwarnings("ignore", category=FutureWarning) + # -- General configuration --------------------------------------------------- project = "Qiskit" From 1f047e2329911bf503b1db765d42c30b27847a39 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 26 Oct 2022 07:48:43 +0200 Subject: [PATCH 23/36] stacklevel=4 --- qiskit/utils/deprecation.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index 392abd6faa10..490c3874fd35 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -29,7 +29,7 @@ def decorator(func): "Adding a 'deprecated' directive to the docstring needs a version. Add parameter `since`" " to `deprecate_arguments` or disable docstring annotation with `modify_docstring=False`" ". This warning will be a QiskitError exception in qiskit-terra 0.23.", - stacklevel=2, + stacklevel=4, category=FutureWarning, ) @@ -75,7 +75,7 @@ def decorator(func): "Adding a 'deprecated' directive to the docstring needs a version. Add parameter `since`" " to `deprecate_function` or disable docstring annotation with `modify_docstring=False`." " This warning will be a QiskitError exception in qiskit-terra 0.23.", - stacklevel=2, + stacklevel=4, category=FutureWarning, ) From 6a5b7105d383a39d1ee5817dc81b18141b066098 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 26 Oct 2022 13:34:27 +0200 Subject: [PATCH 24/36] skip warning when a parameter is qobj --- docs/conf.py | 5 ----- qiskit/utils/deprecation.py | 3 ++- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index 105166d7bc4d..443523cbccde 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -14,11 +14,6 @@ """Sphinx documentation builder.""" -# TODO: remove this line, once Aer adapts to https://github.com/Qiskit/qiskit-terra/pull/8600 -import warnings - -warnings.filterwarnings("ignore", category=FutureWarning) - # -- General configuration --------------------------------------------------- project = "Qiskit" diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index 490c3874fd35..1d6d3901ef35 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -23,7 +23,8 @@ def deprecate_arguments( """Decorator to automatically alias deprecated argument names and warn upon use.""" def decorator(func): - if modify_docstring and since is None: + # TODO Remove this qobj guard once aer updates + if modify_docstring and since is None and "qobj" not in kwarg_map: # TODO: replace with: raise QiskitError( warnings.warn( "Adding a 'deprecated' directive to the docstring needs a version. Add parameter `since`" From c7235ccfc42511b67eac7d3255276d4998390dd4 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 26 Oct 2022 13:48:09 +0200 Subject: [PATCH 25/36] back to error --- qiskit/utils/deprecation.py | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index 1d6d3901ef35..fcfa3cdd9416 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -16,6 +16,8 @@ import warnings from typing import Type +from qiskit.exceptions import QiskitError + def deprecate_arguments( kwarg_map, category: Type[Warning] = DeprecationWarning, modify_docstring=True, since=None @@ -23,15 +25,12 @@ def deprecate_arguments( """Decorator to automatically alias deprecated argument names and warn upon use.""" def decorator(func): - # TODO Remove this qobj guard once aer updates + # TODO Remove the qobj guard once https://github.com/Qiskit/qiskit-aer/pull/1635 is released if modify_docstring and since is None and "qobj" not in kwarg_map: - # TODO: replace with: raise QiskitError( - warnings.warn( + raise QiskitError( "Adding a 'deprecated' directive to the docstring needs a version. Add parameter `since`" " to `deprecate_arguments` or disable docstring annotation with `modify_docstring=False`" - ". This warning will be a QiskitError exception in qiskit-terra 0.23.", - stacklevel=4, - category=FutureWarning, + ". This warning will be a QiskitError exception in qiskit-terra 0.23." ) if modify_docstring and kwarg_map: @@ -71,13 +70,10 @@ def deprecate_function( def decorator(func): if modify_docstring and since is None: - # TODO: replace with: raise QiskitError( - warnings.warn( + raise QiskitError( "Adding a 'deprecated' directive to the docstring needs a version. Add parameter `since`" " to `deprecate_function` or disable docstring annotation with `modify_docstring=False`." - " This warning will be a QiskitError exception in qiskit-terra 0.23.", - stacklevel=4, - category=FutureWarning, + " This warning will be a QiskitError exception in qiskit-terra 0.23." ) if modify_docstring: From 25d1660b8b172fd9a2437481d748f52a0a4b847d Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 26 Oct 2022 13:57:27 +0200 Subject: [PATCH 26/36] conf.py --- docs/conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/conf.py b/docs/conf.py index 443523cbccde..8ebb6d52dbfa 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -36,7 +36,7 @@ "jupyter_sphinx", "sphinx_autodoc_typehints", "reno.sphinxext", - "sphinx_design", + "sphinx_design" ] templates_path = ["_templates"] From 39f28d2e8b1400897e879675d768e73284bca10a Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 26 Oct 2022 13:59:13 +0200 Subject: [PATCH 27/36] adapt message --- qiskit/utils/deprecation.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index fcfa3cdd9416..752f57f1338b 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -29,8 +29,8 @@ def decorator(func): if modify_docstring and since is None and "qobj" not in kwarg_map: raise QiskitError( "Adding a 'deprecated' directive to the docstring needs a version. Add parameter `since`" - " to `deprecate_arguments` or disable docstring annotation with `modify_docstring=False`" - ". This warning will be a QiskitError exception in qiskit-terra 0.23." + " to `deprecate_arguments` or disable docstring annotation with" + "`modify_docstring=False`." ) if modify_docstring and kwarg_map: @@ -73,7 +73,6 @@ def decorator(func): raise QiskitError( "Adding a 'deprecated' directive to the docstring needs a version. Add parameter `since`" " to `deprecate_function` or disable docstring annotation with `modify_docstring=False`." - " This warning will be a QiskitError exception in qiskit-terra 0.23." ) if modify_docstring: From 453cdfc773a0cd73ca5777af84356011ba9eb036 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 26 Oct 2022 14:36:18 +0200 Subject: [PATCH 28/36] back to warning, to avoid braking integration tests --- qiskit/utils/deprecation.py | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index 752f57f1338b..719ec3dafaa6 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -16,8 +16,6 @@ import warnings from typing import Type -from qiskit.exceptions import QiskitError - def deprecate_arguments( kwarg_map, category: Type[Warning] = DeprecationWarning, modify_docstring=True, since=None @@ -27,10 +25,13 @@ def deprecate_arguments( def decorator(func): # TODO Remove the qobj guard once https://github.com/Qiskit/qiskit-aer/pull/1635 is released if modify_docstring and since is None and "qobj" not in kwarg_map: - raise QiskitError( + # TODO: replace with: raise QiskitError( + warnings.warn( "Adding a 'deprecated' directive to the docstring needs a version. Add parameter `since`" - " to `deprecate_arguments` or disable docstring annotation with" - "`modify_docstring=False`." + " to `deprecate_arguments` or disable docstring annotation with `modify_docstring=False`" + ". This warning will be a QiskitError exception in qiskit-terra 0.23.", + stacklevel=4, + category=FutureWarning, ) if modify_docstring and kwarg_map: @@ -70,9 +71,13 @@ def deprecate_function( def decorator(func): if modify_docstring and since is None: - raise QiskitError( + # TODO: replace with: raise QiskitError( + warnings.warn( "Adding a 'deprecated' directive to the docstring needs a version. Add parameter `since`" " to `deprecate_function` or disable docstring annotation with `modify_docstring=False`." + " This warning will be a QiskitError exception in qiskit-terra 0.23.", + stacklevel=4, + category=FutureWarning, ) if modify_docstring: From 3bb43f1ebc141643ad0695f9b054cc727e7626a7 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Sat, 12 Nov 2022 21:35:48 +0100 Subject: [PATCH 29/36] using regex --- qiskit/utils/deprecation.py | 42 ++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index 719ec3dafaa6..565fbc26bdb5 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -12,15 +12,18 @@ """Deprecation utilities""" +import re import functools import warnings from typing import Type +identifier = re.compile("[a-zA-Z_][a-zA-Z0-9_]*") + def deprecate_arguments( kwarg_map, category: Type[Warning] = DeprecationWarning, modify_docstring=True, since=None ): - """Decorator to automatically alias deprecated argument names and warn upon use.""" + """Decorator to automatically alias deprecated argument names and warn upon use.""" def decorator(func): # TODO Remove the qobj guard once https://github.com/Qiskit/qiskit-aer/pull/1635 is released @@ -164,26 +167,27 @@ def _extend_docstring(func, version, kwarg_map): if deprecated_arg and current_indent == arg_indent: new_doc_str_lines.append(docstr_line) deprecated_arg = False - else: - if not deprecated_arg: - for k in kwarg_map.keys(): - if k is None: - continue - if stripped.startswith(k): - arg_indent = len(docstr_line) - len(stripped) - deprecated_arg = True - spaces = " " * arg_indent - new_doc_str_lines.append(spaces + k + ":") - spaces += " " * 4 - new_doc_str_lines += [ - spaces + f".. deprecated:: {version}", - spaces + f" The keyword argument ``{k}`` is deprecated.", - spaces + f" Please, use ``{kwarg_map[k]}`` instead.", - "", - ] - break + elif deprecated_arg: + old_arg_match = identifier.match(stripped) + if old_arg_match: + old_arg = old_arg_match[0] + new_arg = kwarg_map.get(old_arg) + if new_arg: + arg_indent = len(docstr_line) - len(stripped) + deprecated_arg = True + spaces = " " * arg_indent + new_doc_str_lines.append(spaces + old_arg + ":") + spaces += " " * 4 + new_doc_str_lines += [ + spaces + f".. deprecated:: {version}", + spaces + f" The keyword argument ``{old_arg}`` is deprecated.", + spaces + f" Please, use ``{new_arg}`` instead.", + "", + ] else: new_doc_str_lines.append(docstr_line) + else: + new_doc_str_lines.append(docstr_line) else: new_doc_str_lines.append(docstr_line) if docstr_line.lstrip() == "Args:": From f4f54c89a064520f876e4fbdb654930fd9144160 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Sat, 12 Nov 2022 22:07:49 +0100 Subject: [PATCH 30/36] fixing test --- qiskit/utils/deprecation.py | 6 +++--- test/python/utils/test_deprecation.py | 3 +-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index 565fbc26bdb5..78686ea3bef9 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -167,7 +167,7 @@ def _extend_docstring(func, version, kwarg_map): if deprecated_arg and current_indent == arg_indent: new_doc_str_lines.append(docstr_line) deprecated_arg = False - elif deprecated_arg: + else: old_arg_match = identifier.match(stripped) if old_arg_match: old_arg = old_arg_match[0] @@ -186,8 +186,8 @@ def _extend_docstring(func, version, kwarg_map): ] else: new_doc_str_lines.append(docstr_line) - else: - new_doc_str_lines.append(docstr_line) + else: + new_doc_str_lines.append(docstr_line) else: new_doc_str_lines.append(docstr_line) if docstr_line.lstrip() == "Args:": diff --git a/test/python/utils/test_deprecation.py b/test/python/utils/test_deprecation.py index e52447a1b973..22b366a9a848 100644 --- a/test/python/utils/test_deprecation.py +++ b/test/python/utils/test_deprecation.py @@ -60,8 +60,7 @@ def bar_with_deprecated_arg( This is the long description Args: - if_arg1: `if_arg1` description with - multi-line + if_arg1: `if_arg1` description index_arg2: `index_arg2` description other_if_arg1: `other_if_arg1` description From 8f601ad2330e4a7d9d31296e72e8dfa1ae6c7bf4 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Sat, 12 Nov 2022 22:26:49 +0100 Subject: [PATCH 31/36] multi lines and empty --- qiskit/utils/deprecation.py | 2 +- test/python/utils/test_deprecation.py | 37 +++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index 78686ea3bef9..e21bfbcf54ad 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -192,7 +192,7 @@ def _extend_docstring(func, version, kwarg_map): new_doc_str_lines.append(docstr_line) if docstr_line.lstrip() == "Args:": args_section = True - if args_section and docstr_line.lstrip() == "": + if args_section and len(docstr_line.lstrip()) == arg_indent: args_section = False return new_doc_str_lines diff --git a/test/python/utils/test_deprecation.py b/test/python/utils/test_deprecation.py index 22b366a9a848..5e7593bd17a4 100644 --- a/test/python/utils/test_deprecation.py +++ b/test/python/utils/test_deprecation.py @@ -158,3 +158,40 @@ def test_dummayclass_deprecate_arguments(self): int or None: if `if_arg1 == self.arg1`, returns `arg2[index_arg2]` """ self.assertEqual(deprecated_docstring, expected) + + def test_deprecate_arguments_with_empty_lines(self): + """Test deprecate_arguments docstring with empty lines.""" + + def a_function(arg1, arg2, arg3): # pylint: disable=unused-argument, missing-type-doc + """ + This is a description. + + Args: + arg1: text. + text. + + more text + arg2: text + arg3: text + """ + pass + + deprecated_docstring = deprecate_arguments({"arg2": "arg3"}, since="1.2.3")( + a_function + ).__doc__ + expected = """ + This is a description. + + Args: + arg1: text. + text. + + more text + arg2: + .. deprecated:: 1.2.3 + The keyword argument ``arg2`` is deprecated. + Please, use ``arg3`` instead. + + arg3: text + """ + self.assertEqual(deprecated_docstring, expected) From 77c5c2f081e91ff2497fc56fb9fb2f18a3f104ff Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Sat, 12 Nov 2022 22:38:17 +0100 Subject: [PATCH 32/36] type doc support --- qiskit/utils/deprecation.py | 2 +- test/python/utils/test_deprecation.py | 39 +++++++++++++++++++++++++-- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index e21bfbcf54ad..e1c7a5839115 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -176,7 +176,7 @@ def _extend_docstring(func, version, kwarg_map): arg_indent = len(docstr_line) - len(stripped) deprecated_arg = True spaces = " " * arg_indent - new_doc_str_lines.append(spaces + old_arg + ":") + new_doc_str_lines.append(docstr_line.split(": ")[0] + ":") spaces += " " * 4 new_doc_str_lines += [ spaces + f".. deprecated:: {version}", diff --git a/test/python/utils/test_deprecation.py b/test/python/utils/test_deprecation.py index 5e7593bd17a4..3dbfcf87f4ba 100644 --- a/test/python/utils/test_deprecation.py +++ b/test/python/utils/test_deprecation.py @@ -72,7 +72,7 @@ def bar_with_deprecated_arg( return None -class TestDeprecationRaise(QiskitTestCase): +class TestDeprecationDummyClassRaise(QiskitTestCase): """Test deprecation decorators raise warning.""" def assertDeprecationWarning(self, warn, expected_msg): @@ -107,7 +107,7 @@ def test_raise_deprecate_arguments(self): self.assertEqual(output, 1) -class TestDeprecationDocstring(QiskitTestCase): +class TestDeprecationDummyClassDocstring(QiskitTestCase): """Test deprecation decorators docstring modification for DummyClass.""" def test_dummyclass_deprecate_function(self): @@ -159,6 +159,10 @@ def test_dummayclass_deprecate_arguments(self): """ self.assertEqual(deprecated_docstring, expected) + +class TestDeprecationDocstring(QiskitTestCase): + """Test for docstring modification with several corner cases""" + def test_deprecate_arguments_with_empty_lines(self): """Test deprecate_arguments docstring with empty lines.""" @@ -195,3 +199,34 @@ def a_function(arg1, arg2, arg3): # pylint: disable=unused-argument, missing-ty arg3: text """ self.assertEqual(deprecated_docstring, expected) + + def test_deprecate_arguments_with_types(self): + """Test deprecate_arguments docstring with type docs.""" + + def a_function(arg1, arg2, arg3): # pylint: disable=unused-argument + """ + This is a description. + + Args: + arg1 (int): text + arg2 (str): text + arg3 (str): text + """ + pass + + deprecated_docstring = deprecate_arguments({"arg2": "arg3"}, since="1.2.3")( + a_function + ).__doc__ + expected = """ + This is a description. + + Args: + arg1 (int): text + arg2 (str): + .. deprecated:: 1.2.3 + The keyword argument ``arg2`` is deprecated. + Please, use ``arg3`` instead. + + arg3 (str): text + """ + self.assertEqual(deprecated_docstring, expected) From 82aaba972455b255b477b118703349080a7fae08 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 24 Jan 2023 20:45:09 +0100 Subject: [PATCH 33/36] DeprecationWarning to PendingDeprecationWarning --- .../eigen_solvers/numpy_eigen_solver.py | 2 +- qiskit/algorithms/eigen_solvers/vqd.py | 2 +- .../algorithms/evolvers/evolution_problem.py | 2 +- qiskit/algorithms/evolvers/evolution_result.py | 2 +- .../evolvers/trotterization/trotter_qrte.py | 2 +- .../numpy_minimum_eigen_solver.py | 2 +- .../algorithms/minimum_eigen_solvers/qaoa.py | 2 +- qiskit/algorithms/minimum_eigen_solvers/vqe.py | 2 +- .../algorithms/time_evolvers/test_pvqd.py | 18 ++++++++++-------- 9 files changed, 18 insertions(+), 16 deletions(-) diff --git a/qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py b/qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py index 784108e4d141..4125a4b7d85f 100644 --- a/qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py +++ b/qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py @@ -52,7 +52,7 @@ class NumPyEigensolver(Eigensolver): @deprecate_function( "The NumPyEigensolver class has been superseded by the " "qiskit.algorithms.eigensolvers.NumPyEigensolver class. ", - category=DeprecationWarning, + category=PendingDeprecationWarning, since="0.23.0", ) def __init__( diff --git a/qiskit/algorithms/eigen_solvers/vqd.py b/qiskit/algorithms/eigen_solvers/vqd.py index fae6c374dae7..ef5542af088a 100644 --- a/qiskit/algorithms/eigen_solvers/vqd.py +++ b/qiskit/algorithms/eigen_solvers/vqd.py @@ -98,7 +98,7 @@ class VQD(VariationalAlgorithm, Eigensolver): @deprecate_function( "The VQD class has been superseded by the " "qiskit.algorithms.eigensolvers.VQD class. ", - category=DeprecationWarning, + category=PendingDeprecationWarning, since="0.23.0", ) def __init__( diff --git a/qiskit/algorithms/evolvers/evolution_problem.py b/qiskit/algorithms/evolvers/evolution_problem.py index 6b33428da362..4344c60c8152 100644 --- a/qiskit/algorithms/evolvers/evolution_problem.py +++ b/qiskit/algorithms/evolvers/evolution_problem.py @@ -36,7 +36,7 @@ class EvolutionProblem: @deprecate_function( "The EvolutionProblem class has been superseded by the " "qiskit.algorithms.time_evolvers.TimeEvolutionProblem class. ", - category=DeprecationWarning, + category=PendingDeprecationWarning, since="0.23.0", ) def __init__( diff --git a/qiskit/algorithms/evolvers/evolution_result.py b/qiskit/algorithms/evolvers/evolution_result.py index 870cdbd23b3a..57507660d1ee 100644 --- a/qiskit/algorithms/evolvers/evolution_result.py +++ b/qiskit/algorithms/evolvers/evolution_result.py @@ -34,7 +34,7 @@ class EvolutionResult(AlgorithmResult): @deprecate_function( "The EvolutionResult class has been superseded by the " "qiskit.algorithms.time_evolvers.TimeEvolutionResult class. ", - category=DeprecationWarning, + category=PendingDeprecationWarning, since="0.23.0", ) def __init__( diff --git a/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py index c3a2b4009e01..273c5e86eba2 100644 --- a/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py +++ b/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py @@ -67,7 +67,7 @@ class TrotterQRTE(RealEvolver): @deprecate_function( "The TrotterQRTE class has been superseded by the " "qiskit.algorithms.time_evolvers.trotterization.TrotterQRTE class. ", - category=DeprecationWarning, + category=PendingDeprecationWarning, since="0.23.0", ) def __init__( diff --git a/qiskit/algorithms/minimum_eigen_solvers/numpy_minimum_eigen_solver.py b/qiskit/algorithms/minimum_eigen_solvers/numpy_minimum_eigen_solver.py index 71c4791428cd..9bcb37e2105f 100644 --- a/qiskit/algorithms/minimum_eigen_solvers/numpy_minimum_eigen_solver.py +++ b/qiskit/algorithms/minimum_eigen_solvers/numpy_minimum_eigen_solver.py @@ -40,7 +40,7 @@ class NumPyMinimumEigensolver(MinimumEigensolver): @deprecate_function( "The NumPyMinimumEigensolver class has been superseded by the " "qiskit.algorithms.minimum_eigensolvers.NumPyMinimumEigensolver class. ", - category=DeprecationWarning, + category=PendingDeprecationWarning, since="0.23.0", ) def __init__( diff --git a/qiskit/algorithms/minimum_eigen_solvers/qaoa.py b/qiskit/algorithms/minimum_eigen_solvers/qaoa.py index 7ac945346de9..914522efa3ac 100644 --- a/qiskit/algorithms/minimum_eigen_solvers/qaoa.py +++ b/qiskit/algorithms/minimum_eigen_solvers/qaoa.py @@ -62,7 +62,7 @@ class QAOA(VQE): @deprecate_function( "The QAOA class has been superseded by the " "qiskit.algorithms.minimum_eigensolvers.QAOA class. ", - category=DeprecationWarning, + category=PendingDeprecationWarning, since="0.23.0", ) def __init__( diff --git a/qiskit/algorithms/minimum_eigen_solvers/vqe.py b/qiskit/algorithms/minimum_eigen_solvers/vqe.py index 83da52dbc323..c9a4aeff1db4 100644 --- a/qiskit/algorithms/minimum_eigen_solvers/vqe.py +++ b/qiskit/algorithms/minimum_eigen_solvers/vqe.py @@ -130,7 +130,7 @@ def my_minimizer(fun, x0, jac=None, bounds=None) -> OptimizerResult: @deprecate_function( "The VQE class has been superseded by the " "qiskit.algorithms.minimum_eigensolvers.VQE class. ", - category=DeprecationWarning, + category=PendingDeprecationWarning, since="0.23.0", ) def __init__( diff --git a/test/python/algorithms/time_evolvers/test_pvqd.py b/test/python/algorithms/time_evolvers/test_pvqd.py index 70cb12520e84..55c7c0f45ba7 100644 --- a/test/python/algorithms/time_evolvers/test_pvqd.py +++ b/test/python/algorithms/time_evolvers/test_pvqd.py @@ -18,7 +18,7 @@ from ddt import data, ddt, unpack from qiskit import QiskitError -from qiskit.algorithms.evolvers import EvolutionProblem +from qiskit.algorithms.time_evolvers import TimeEvolutionProblem from qiskit.algorithms.optimizers import L_BFGS_B, SPSA, GradientDescent, OptimizerResult from qiskit.algorithms.state_fidelities import ComputeUncompute from qiskit.algorithms.time_evolvers.pvqd import PVQD @@ -96,7 +96,9 @@ def test_pvqd(self, hamiltonian_type, gradient, num_timesteps): optimizer=optimizer, num_timesteps=num_timesteps, ) - problem = EvolutionProblem(hamiltonian, time, aux_operators=[hamiltonian, self.observable]) + problem = TimeEvolutionProblem( + hamiltonian, time, aux_operators=[hamiltonian, self.observable] + ) result = pvqd.evolve(problem) self.assertTrue(len(result.fidelities) == 3) @@ -176,7 +178,7 @@ def test_invalid_num_timestep(self): optimizer=L_BFGS_B(), num_timesteps=0, ) - problem = EvolutionProblem( + problem = TimeEvolutionProblem( self.hamiltonian, time=0.01, aux_operators=[self.hamiltonian, self.observable] ) @@ -199,7 +201,7 @@ def test_initial_guess_and_observables(self): num_timesteps=10, initial_guess=initial_guess, ) - problem = EvolutionProblem( + problem = TimeEvolutionProblem( self.hamiltonian, time=0.1, aux_operators=[self.hamiltonian, self.observable] ) @@ -211,7 +213,7 @@ def test_initial_guess_and_observables(self): def test_zero_parameters(self): """Test passing an ansatz with zero parameters raises an error.""" - problem = EvolutionProblem(self.hamiltonian, time=0.02) + problem = TimeEvolutionProblem(self.hamiltonian, time=0.02) sampler = Sampler() fidelity_primitive = ComputeUncompute(sampler) @@ -230,7 +232,7 @@ def test_initial_state_raises(self): initial_state = QuantumCircuit(2) initial_state.x(0) - problem = EvolutionProblem( + problem = TimeEvolutionProblem( self.hamiltonian, time=0.02, initial_state=initial_state, @@ -252,7 +254,7 @@ def test_initial_state_raises(self): def test_aux_ops_raises(self): """Test passing auxiliary operators with no estimator raises an error.""" - problem = EvolutionProblem( + problem = TimeEvolutionProblem( self.hamiltonian, time=0.02, aux_operators=[self.hamiltonian, self.observable] ) @@ -321,7 +323,7 @@ def test_gradient_supported(self): estimator=estimator, optimizer=optimizer, ) - problem = EvolutionProblem(self.hamiltonian, time=0.01) + problem = TimeEvolutionProblem(self.hamiltonian, time=0.01) for circuit, expected_support in tests: with self.subTest(circuit=circuit, expected_support=expected_support): pvqd.ansatz = circuit From 97472d3d38bc896df88e363e3b29bb7cabc1ea29 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 25 Jan 2023 07:38:47 +0100 Subject: [PATCH 34/36] DeprecationWarning to PendingDeprecationWarning --- qiskit/algorithms/minimum_eigen_solvers/minimum_eigen_solver.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qiskit/algorithms/minimum_eigen_solvers/minimum_eigen_solver.py b/qiskit/algorithms/minimum_eigen_solvers/minimum_eigen_solver.py index 78aec0431dc2..bf7a4b8448be 100644 --- a/qiskit/algorithms/minimum_eigen_solvers/minimum_eigen_solver.py +++ b/qiskit/algorithms/minimum_eigen_solvers/minimum_eigen_solver.py @@ -94,7 +94,7 @@ class MinimumEigensolverResult(AlgorithmResult): @deprecate_function( "The MinimumEigensolverResult class has been superseded by the " "qiskit.algorithms.minimum_eigensolvers.MinimumEigensolverResult class.", - category=DeprecationWarning, + category=PendingDeprecationWarning, since="0.23.0", ) def __init__(self) -> None: From 5e8298fc4483c7839d41fd4a68a19c34a90cddfa Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 25 Jan 2023 10:02:36 +0100 Subject: [PATCH 35/36] DeprecationWarning to PendingDeprecationWarning --- qiskit/algorithms/eigen_solvers/eigen_solver.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qiskit/algorithms/eigen_solvers/eigen_solver.py b/qiskit/algorithms/eigen_solvers/eigen_solver.py index 04c81efebbb4..1eab2e8b625c 100644 --- a/qiskit/algorithms/eigen_solvers/eigen_solver.py +++ b/qiskit/algorithms/eigen_solvers/eigen_solver.py @@ -90,7 +90,7 @@ class EigensolverResult(AlgorithmResult): @deprecate_function( "The EigensolverResult class has been superseded by the " "qiskit.algorithms.eigensolvers.EigensolverResult class. ", - category=DeprecationWarning, + category=PendingDeprecationWarning, since="0.23.0", ) def __init__(self) -> None: From 1fb35ece300e6a7ef5329f9f62e62d30b416c6d0 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 25 Jan 2023 12:48:19 +0100 Subject: [PATCH 36/36] DeprecationWarning to PendingDeprecationWarning --- qiskit/algorithms/aux_ops_evaluator.py | 2 +- qiskit/algorithms/eigen_solvers/vqd.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/qiskit/algorithms/aux_ops_evaluator.py b/qiskit/algorithms/aux_ops_evaluator.py index f46bfd9ce90b..87c9cb9427a2 100644 --- a/qiskit/algorithms/aux_ops_evaluator.py +++ b/qiskit/algorithms/aux_ops_evaluator.py @@ -34,7 +34,7 @@ @deprecate_function( "The eval_observables function has been superseded by the " "qiskit.algorithms.observables_evaluator.estimate_observables function. ", - category=DeprecationWarning, + category=PendingDeprecationWarning, since="0.23.0", ) def eval_observables( diff --git a/qiskit/algorithms/eigen_solvers/vqd.py b/qiskit/algorithms/eigen_solvers/vqd.py index ef5542af088a..f7ae5142e844 100644 --- a/qiskit/algorithms/eigen_solvers/vqd.py +++ b/qiskit/algorithms/eigen_solvers/vqd.py @@ -767,7 +767,7 @@ class VQDResult(VariationalResult, EigensolverResult): @deprecate_function( "The VQDResult class has been superseded by the " "qiskit.algorithms.eigensolvers.VQDResult class. ", - category=DeprecationWarning, + category=PendingDeprecationWarning, since="0.23.0", ) def __init__(self) -> None: