From 416456897859571c838e7b65a8f0168433d88f08 Mon Sep 17 00:00:00 2001 From: Matthew Treinish Date: Thu, 7 Nov 2019 13:32:11 -0500 Subject: [PATCH] Make ibmq imports for backend monitor at runtime (#3429) After #3325 the import structure of the tools directory was changed so that sometimes the ibmq imports at the top of the qiskit.tools.monitor.backend_overview module get evaluated prior to the pkgutil call in qiskit.providers.__init__ that is used to look for namespace packages outside of the terra repo. When this happens the imports from the qiskit-ibmq-provider package fail because they haven't been added to the python namespace yet. The way the backend monitor was checking made this non-fatal but would never populate the names. So when you'd later go to run the function it would fail with a NameError because the imports didn't work, even if ibmq was installed (and working otherwise). This commit works around this issue by making the ibmq imports occur at runtime inside the functions in the module. This makes the imports happen as late as possible and ensures that if ibmq is installed and working that we'll be checking that after pkgutil has a chance to search for the namespace packages. Related-To Qiskit/qiskit#559 Fixes #3413 --- qiskit/tools/monitor/backend_overview.py | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/qiskit/tools/monitor/backend_overview.py b/qiskit/tools/monitor/backend_overview.py index 3705d2595c..9c4d496a03 100644 --- a/qiskit/tools/monitor/backend_overview.py +++ b/qiskit/tools/monitor/backend_overview.py @@ -19,12 +19,6 @@ import math from qiskit.exceptions import QiskitError -try: - # pylint: disable=import-error,no-name-in-module - from qiskit.providers.ibmq import IBMQ, IBMQBackend -except ImportError: - pass - def get_unique_backends(): """Gets the unique backends that are available. @@ -34,7 +28,14 @@ def get_unique_backends(): Raises: QiskitError: No backends available. + ImportError: If qiskit-ibmq-provider is not installed """ + try: + from qiskit.providers.ibmq import IBMQ + except ImportError: + raise ImportError("The IBMQ provider is necessary for this function " + " to work. Please ensure it's installed before " + "using this function") backends = [] for provider in IBMQ.providers(): for backend in provider.backends(): @@ -57,7 +58,16 @@ def backend_monitor(backend): backend (IBMQBackend): Backend to monitor. Raises: QiskitError: Input is not a IBMQ backend. + ImportError: If qiskit-ibmq-provider is not installed """ + try: + # pylint: disable=import-error,no-name-in-module + from qiskit.providers.ibmq import IBMQBackend + except ImportError: + raise ImportError("The IBMQ provider is necessary for this function " + " to work. Please ensure it's installed before " + "using this function") + if not isinstance(backend, IBMQBackend): raise QiskitError('Input variable is not of type IBMQBackend.') config = backend.configuration().to_dict()