Skip to content

Avoid potential import cycles from Aer and IBMQ #5532

@mtreinish

Description

@mtreinish

What is the expected enhancement?

Right now the effort to remove namespace packaging in #5089 is blocked on the modules level imports of Aer and IBMQ. This is because this causes an import cycle when those factory objects are no longer in the qiskit namespace. Basically, qiskit_aer imports qiskit whichi imports qiskit_aer.Aer which can't be resolved by python. To move forward on this we need to make these objects lazily load qiskit.providers.aer/qiskit_aer and qiskit.providers.ibmq/qiskit_ibmq_provider. The easiest way to handle this is to wait for python 3.7 to be the minimum python version and then we can just use a module level __getattr__ and import when Aer or IBMQ are accessed. But that is likely 6+ months away since 0.17.0 will start the deprecation timer on Python 3.6 support. In the meantime we should be able do something like:

class _AerWrapper:

    def __init__(self):
       self.aer = None
       
    def __getattr__(self, attr):
       if self._aer is None:
           try:
                from qiskit.providers.aer import Aer
            except ImportError:
                raise ImportError("useful message")
            self.aer = Aer
      return getattr(self.aer, attr)

(note this is completely untested, just my rough idea).

This should hopefully enable us to remove the import cycle at the module level. It would also have a noticeable benefit for #5100 as we're not unconditionally importing ibmq and aer all the time.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions