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
This commit is contained in:
Matthew Treinish 2019-11-07 13:32:11 -05:00 committed by Kevin Krsulich
parent 9d2517403a
commit 4164568978
1 changed files with 16 additions and 6 deletions

View File

@ -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()