Repository: PennyLaneAI/pennylane

Issue:
Unify import shortcuts used in the library and tests
Currently, we have unified mostly around

```python
import pennylane as qml
```

However, there are a few places where this is not the case. These include:

* `qnode.py` (`import pennylane` and `pennylane.operation`)

* `test_operation.py` (`import pennylane.ops as oo`)

These should be changed (as well as any additional cases) to `import pennylane as qml`.
Unify import shortcuts used in the library and tests
Currently, we have unified mostly around

```python
import pennylane as qml
```

However, there are a few places where this is not the case. These include:

* `qnode.py` (`import pennylane` and `pennylane.operation`)

* `test_operation.py` (`import pennylane.ops as oo`)

These should be changed (as well as any additional cases) to `import pennylane as qml`.


Discussion:

Resolving patch:
diff --git a/pennylane/qnode.py b/pennylane/qnode.py
--- a/pennylane/qnode.py
+++ b/pennylane/qnode.py
@@ -136,8 +136,7 @@ def my_quantum_function(x, y):
 
 from scipy import linalg
 
-import pennylane
-import pennylane.operation
+import pennylane as qml
 
 from pennylane.utils import _flatten, unflatten, _inv_dict, _get_default_args, expand, CircuitGraph
 from .variable import Variable
@@ -222,7 +221,7 @@ def _append_op(self, op):
             op (:class:`~.operation.Operation`): quantum operation to be added to the circuit
         """
         # EVs go to their own, temporary queue
-        if isinstance(op, pennylane.operation.Observable):
+        if isinstance(op, qml.operation.Observable):
             if op.return_type is None:
                 self.queue.append(op)
             else:
@@ -310,8 +309,8 @@ def construct(self, args, kwargs=None):
         # check the validity of the circuit
 
         # quantum circuit function return validation
-        if isinstance(res, pennylane.operation.Observable):
-            if res.return_type is pennylane.operation.Sample:
+        if isinstance(res, qml.operation.Observable):
+            if res.return_type is qml.operation.Sample:
                 # Squeezing ensures that there is only one array of values returned
                 # when only a single-mode sample is requested
                 self.output_conversion = np.squeeze
@@ -320,7 +319,7 @@ def construct(self, args, kwargs=None):
 
             self.output_dim = 1
             res = (res,)
-        elif isinstance(res, Sequence) and res and all(isinstance(x, pennylane.operation.Observable) for x in res):
+        elif isinstance(res, Sequence) and res and all(isinstance(x, qml.operation.Observable) for x in res):
             # for multiple observables values, any valid Python sequence of observables
             # (i.e., lists, tuples, etc) are supported in the QNode return statement.
 
@@ -349,7 +348,7 @@ def construct(self, args, kwargs=None):
         self.ops = self.queue + self.ev  #: list[Operation]: combined list of circuit operations
 
         # classify the circuit contents
-        temp = [isinstance(op, pennylane.operation.CV) for op in self.ops if not isinstance(op, pennylane.ops.Identity)]
+        temp = [isinstance(op, qml.operation.CV) for op in self.ops if not isinstance(op, qml.ops.Identity)]
 
         if all(temp):
             self.type = 'CV'
@@ -428,21 +427,21 @@ def construct_metric_tensor(self, args, **kwargs):
                 # to the generator of the current operation
                 if isinstance(gen, np.ndarray):
                     # generator is a Hermitian matrix
-                    variance = pennylane.var(pennylane.Hermitian(gen, w, do_queue=False))
+                    variance = qml.var(qml.Hermitian(gen, w, do_queue=False))
 
                     if not diag_approx:
                         Ki_matrices.append((n, expand(gen, w, self.num_wires)))
 
-                elif issubclass(gen, pennylane.operation.Observable):
+                elif issubclass(gen, qml.operation.Observable):
                     # generator is an existing PennyLane operation
-                    variance = pennylane.var(gen(w, do_queue=False))
+                    variance = qml.var(gen(w, do_queue=False))
 
                     if not diag_approx:
-                        if issubclass(gen, pennylane.ops.PauliX):
+                        if issubclass(gen, qml.ops.PauliX):
                             mat = np.array([[0, 1], [1, 0]])
-                        elif issubclass(gen, pennylane.ops.PauliY):
+                        elif issubclass(gen, qml.ops.PauliY):
                             mat = np.array([[0, -1j], [1j, 0]])
-                        elif issubclass(gen, pennylane.ops.PauliZ):
+                        elif issubclass(gen, qml.ops.PauliZ):
                             mat = np.array([[1, 0], [0, -1]])
 
                         Ki_matrices.append((n, expand(mat, w, self.num_wires)))
@@ -522,9 +521,9 @@ def _op_successors(self, o_idx, only='G'):
         #
         # if it is in a topological order? the docs aren't clear.
         if only == 'E':
-            return list(filter(lambda x: isinstance(x, pennylane.operation.Observable), succ))
+            return list(filter(lambda x: isinstance(x, qml.operation.Observable), succ))
         if only == 'G':
-            return list(filter(lambda x: not isinstance(x, pennylane.operation.Observable), succ))
+            return list(filter(lambda x: not isinstance(x, qml.operation.Observable), succ))
         return succ
 
     def _best_method(self, idx):
@@ -563,7 +562,7 @@ def best_for_op(o_idx):
             "Returns the best gradient method for the operation op."
             op = self.ops[o_idx]
             # for discrete operations, other ops do not affect the choice
-            if not isinstance(op, pennylane.operation.CV):
+            if not isinstance(op, qml.operation.CV):
                 return op.grad_method
 
             # for CV ops it is more complicated
@@ -581,7 +580,7 @@ def best_for_op(o_idx):
                         if x.ev_order is None:
                             return 'F'
                         if x.ev_order == 2:
-                            if x.return_type is pennylane.operation.Variance:
+                            if x.return_type is qml.operation.Variance:
                                 # second order observables don't support
                                 # analytic diff of variances
                                 return 'F'
@@ -726,7 +725,7 @@ def metric_tensor(self, *args, **kwargs):
             if not diag_approx:
                 # block diagonal approximation
 
-                unitary_op = pennylane.ops.QubitUnitary(V, wires=list(range(self.num_wires)), do_queue=False)
+                unitary_op = qml.ops.QubitUnitary(V, wires=list(range(self.num_wires)), do_queue=False)
                 self.device.execute(circuit['queue'] + [unitary_op], circuit['observable'])
                 probs = list(self.device.probability().values())
 
@@ -847,7 +846,7 @@ def jacobian(self, params, which=None, *, method='B', h=1e-7, order=1, **kwargs)
             # construct the circuit
             self.construct(params, circuit_kwargs)
 
-        sample_ops = [e for e in self.ev if e.return_type is pennylane.operation.Sample]
+        sample_ops = [e for e in self.ev if e.return_type is qml.operation.Sample]
         if sample_ops:
             names = [str(e) for e in sample_ops]
             raise QuantumFunctionError("Circuits that include sampling can not be differentiated. "
@@ -893,7 +892,7 @@ def check_method(m):
             else:
                 y0 = None
 
-        variances = any(e.return_type is pennylane.operation.Variance for e in self.ev)
+        variances = any(e.return_type is qml.operation.Variance for e in self.ev)
 
         # compute the partial derivative w.r.t. each parameter using the proper method
         grad = np.zeros((self.output_dim, len(which)), dtype=float)
@@ -1046,7 +1045,7 @@ def tr_obs(ex):
                     if q.ndim == 2:
                         # 2nd order observable
                         qp = qp +qp.T
-                    return pennylane.expval(pennylane.PolyXP(qp, wires=range(w), do_queue=False))
+                    return qml.expval(qml.PolyXP(qp, wires=range(w), do_queue=False))
 
                 # transform the observables
                 obs = list(map(tr_obs, self.ev))
@@ -1075,20 +1074,20 @@ def _pd_analytic_var(self, param_values, param_idx, **kwargs):
 
         # boolean mask: elements are True where the
         # return type is a variance, False for expectations
-        where_var = [e.return_type is pennylane.operation.Variance for e in self.ev]
+        where_var = [e.return_type is qml.operation.Variance for e in self.ev]
 
         for i, e in enumerate(self.ev):
             # iterate through all observables
             # here, i is the index of the observable
             # and e is the observable
 
-            if e.return_type is not pennylane.operation.Variance:
+            if e.return_type is not qml.operation.Variance:
                 # if the expectation value is not a variance
                 # continue on to the next loop iteration
                 continue
 
             # temporarily convert return type to expectation
-            self.ev[i].return_type = pennylane.operation.Expectation
+            self.ev[i].return_type = qml.operation.Expectation
 
             # analytic derivative of <A^2>
             # For involutory observables (A^2 = I),
@@ -1109,7 +1108,7 @@ def _pd_analytic_var(self, param_values, param_idx, **kwargs):
                         old = copy.deepcopy(e)
 
                         # replace the Hermitian variance with <A^2> expectation
-                        self.ev[i] = pennylane.expval(pennylane.ops.Hermitian(A @ A, w, do_queue=False))
+                        self.ev[i] = qml.expval(qml.ops.Hermitian(A @ A, w, do_queue=False))
 
                         # calculate the analytic derivative of <A^2>
                         pdA2 = np.asarray(self._pd_analytic(param_values, param_idx, **kwargs))
@@ -1138,7 +1137,7 @@ def _pd_analytic_var(self, param_values, param_idx, **kwargs):
 
                 # replace the first order observable var(A) with <A^2>
                 # in the return queue
-                self.ev[i] = pennylane.expval(pennylane.ops.PolyXP(A, w, do_queue=False))
+                self.ev[i] = qml.expval(qml.ops.PolyXP(A, w, do_queue=False))
 
                 # calculate the analytic derivative of <A^2>
                 pdA2 = np.asarray(self._pd_analytic(param_values, param_idx, force_order2=True, **kwargs))


Test patch:
diff --git a/tests/test_about.py b/tests/test_about.py
--- a/tests/test_about.py
+++ b/tests/test_about.py
@@ -15,7 +15,7 @@
 Unit tests for the :mod:`pennylane` configuration classe :class:`Configuration`.
 """
 # pylint: disable=protected-access
-import pennylane
+import pennylane as qml
 import pytest
 import re
 
@@ -24,11 +24,11 @@ def test_about(capfd):
     """
     about: Tests if the about string prints correct.
     """
-    pennylane.about()
+    qml.about()
     out, err = capfd.readouterr()
     assert "Version:" in out
     pl_version_match = re.search(r"Version:\s+([\S]+)\n", out).group(1)
-    assert pennylane.version().replace("-", ".") in pl_version_match
+    assert qml.version().replace("-", ".") in pl_version_match
     assert "Numpy version" in out
     assert "Scipy version" in out
     assert "default.qubit" in out
diff --git a/tests/test_operation.py b/tests/test_operation.py
--- a/tests/test_operation.py
+++ b/tests/test_operation.py
@@ -21,12 +21,9 @@
 import numpy as np
 import numpy.random as nr
 
-from defaults import pennylane, BaseTest
-import pennylane.operation as oo
-import pennylane.variable as ov
+from defaults import pennylane as qml, BaseTest
 
-
-dev = pennylane.device('default.qubit', wires=2)
+dev = qml.device('default.qubit', wires=2)
 
 
 class BasicTest(BaseTest):
@@ -54,7 +51,7 @@ def h_test(cls):
 
             op = cls(*par, wires=ww, do_queue=False)
 
-            if issubclass(cls, oo.Observable):
+            if issubclass(cls, qml.operation.Observable):
                 Q = op.heisenberg_obs(0)
                 # ev_order equals the number of dimensions of the H-rep array
                 self.assertEqual(Q.ndim, cls.ev_order)
@@ -102,8 +99,8 @@ def h_test(cls):
                 U_high_order = np.array([U] * 3)
                 op.heisenberg_expand(U_high_order, len(op.wires))
 
-        for op in pennylane.ops._cv__ops__ | pennylane.ops._cv__obs__:
-            cls = getattr(pennylane.ops, op)
+        for op in qml.ops._cv__ops__ | qml.ops._cv__obs__:
+            cls = getattr(qml.ops, op)
             if cls.supports_heisenberg:  # only test gaussian operations
                 h_test(cls)
 
@@ -158,7 +155,7 @@ def op_test(cls):
                     cls(*n*[0.0], wires=ww, do_queue=False)
                 # params must not be Variables
                 with self.assertRaisesRegex(TypeError, 'Array parameter expected'):
-                    cls(*n*[ov.Variable(0)], wires=ww, do_queue=False)
+                    cls(*n*[qml.variable.Variable(0)], wires=ww, do_queue=False)
             elif cls.par_domain == 'N':
                 # params must be natural numbers
                 with self.assertRaisesRegex(TypeError, 'Natural number'):
@@ -181,33 +178,33 @@ def op_test(cls):
             cls.par_domain = tmp
 
 
-        for cls in pennylane.ops._qubit__ops__:
-            op_test(getattr(pennylane.ops, cls))
+        for cls in qml.ops._qubit__ops__:
+            op_test(getattr(qml.ops, cls))
 
-        for cls in pennylane.ops._cv__ops__:
-            op_test(getattr(pennylane.ops, cls))
+        for cls in qml.ops._cv__ops__:
+            op_test(getattr(qml.ops, cls))
 
-        for cls in pennylane.ops._qubit__obs__:
-            op_test(getattr(pennylane.ops, cls))
+        for cls in qml.ops._qubit__obs__:
+            op_test(getattr(qml.ops, cls))
 
-        for cls in pennylane.ops._cv__obs__:
-            op_test(getattr(pennylane.ops, cls))
+        for cls in qml.ops._cv__obs__:
+            op_test(getattr(qml.ops, cls))
 
     def test_operation_outside_queue(self):
         """Test that an error is raised if an operation is called
         outside of a QNode context."""
         self.logTestName()
 
-        with self.assertRaisesRegex(pennylane.QuantumFunctionError, "can only be used inside a qfunc"):
-            pennylane.ops.Hadamard(wires=0)
+        with self.assertRaisesRegex(qml.QuantumFunctionError, "can only be used inside a qfunc"):
+            qml.ops.Hadamard(wires=0)
 
     def test_operation_no_queue(self):
         """Test that an operation can be called outside a QNode with the do_queue flag"""
         self.logTestName()
 
         try:
-            pennylane.ops.Hadamard(wires=0, do_queue=False)
-        except pennylane.QuantumFunctionError:
+            qml.ops.Hadamard(wires=0, do_queue=False)
+        except qml.QuantumFunctionError:
             self.fail("Operation failed to instantiate outside of QNode with do_queue=False.")
 
 
@@ -218,7 +215,7 @@ def test_incorrect_num_wires(self):
         """Test that an exception is raised if called with wrong number of wires"""
         self.logTestName()
 
-        class DummyOp(oo.Operation):
+        class DummyOp(qml.operation.Operation):
             r"""Dummy custom operation"""
             num_wires = 1
             num_params = 1
@@ -232,7 +229,7 @@ def test_incorrect_num_params(self):
         """Test that an exception is raised if called with wrong number of parameters"""
         self.logTestName()
 
-        class DummyOp(oo.Operation):
+        class DummyOp(qml.operation.Operation):
             r"""Dummy custom operation"""
             num_wires = 1
             num_params = 1
@@ -246,7 +243,7 @@ def test_incorrect_param_domain(self):
         """Test that an exception is raised if an incorrect parameter domain is requested"""
         self.logTestName()
 
-        class DummyOp(oo.Operation):
+        class DummyOp(qml.operation.Operation):
             r"""Dummy custom operation"""
             num_wires = 1
             num_params = 1
@@ -260,7 +257,7 @@ def test_incorrect_grad_recipe_length(self):
         """Test that an exception is raised if len(grad_recipe)!=len(num_params)"""
         self.logTestName()
 
-        class DummyOp(oo.CVOperation):
+        class DummyOp(qml.operation.CVOperation):
             r"""Dummy custom operation"""
             num_wires = 1
             num_params = 1
@@ -275,7 +272,7 @@ def test_grad_method_with_integer_params(self):
         """Test that an exception is raised if a non-None grad-method is provided for natural number params"""
         self.logTestName()
 
-        class DummyOp(oo.Operation):
+        class DummyOp(qml.operation.Operation):
             r"""Dummy custom operation"""
             num_wires = 1
             num_params = 1
@@ -289,7 +286,7 @@ def test_analytic_grad_with_array_param(self):
         """Test that an exception is raised if an analytic gradient is requested with an array param"""
         self.logTestName()
 
-        class DummyOp(oo.Operation):
+        class DummyOp(qml.operation.Operation):
             r"""Dummy custom operation"""
             num_wires = 1
             num_params = 1
@@ -303,7 +300,7 @@ def test_numerical_grad_with_grad_recipe(self):
         """Test that an exception is raised if a numerical gradient is requested with a grad recipe"""
         self.logTestName()
 
-        class DummyOp(oo.Operation):
+        class DummyOp(qml.operation.Operation):
             r"""Dummy custom operation"""
             num_wires = 1
             num_params = 1
@@ -318,7 +315,7 @@ def test_variable_instead_of_array(self):
         """Test that an exception is raised if an array is expected but a variable is passed"""
         self.logTestName()
 
-        class DummyOp(oo.Operation):
+        class DummyOp(qml.operation.Operation):
             r"""Dummy custom operation"""
             num_wires = 1
             num_params = 1
@@ -326,7 +323,7 @@ class DummyOp(oo.Operation):
             grad_method = 'A'
 
         with self.assertRaisesRegex(TypeError, "Array parameter expected, got a Variable"):
-            DummyOp(ov.Variable(0), wires=[0], do_queue=False)
+            DummyOp(qml.variable.Variable(0), wires=[0], do_queue=False)
 
     def test_array_instead_of_flattened_array(self):
         """Test that an exception is raised if an array is expected, but an array is passed
@@ -334,7 +331,7 @@ def test_array_instead_of_flattened_array(self):
         accessible by the developer or the user, but is kept in case it will be used in the future."""
         self.logTestName()
 
-        class DummyOp(oo.Operation):
+        class DummyOp(qml.operation.Operation):
             r"""Dummy custom operation"""
             num_wires = 1
             num_params = 1
@@ -349,7 +346,7 @@ def test_scalar_instead_of_array(self):
         """Test that an exception is raised if an array is expected but a scalar is passed"""
         self.logTestName()
 
-        class DummyOp(oo.Operation):
+        class DummyOp(qml.operation.Operation):
             r"""Dummy custom operation"""
             num_wires = 1
             num_params = 1
@@ -363,7 +360,7 @@ def test_array_instead_of_real(self):
         """Test that an exception is raised if a real number is expected but an array is passed"""
         self.logTestName()
 
-        class DummyOp(oo.Operation):
+        class DummyOp(qml.operation.Operation):
             r"""Dummy custom operation"""
             num_wires = 1
             num_params = 1
@@ -377,7 +374,7 @@ def test_not_natural_param(self):
         """Test that an exception is raised if a natural number is expected but not passed"""
         self.logTestName()
 
-        class DummyOp(oo.Operation):
+        class DummyOp(qml.operation.Operation):
             r"""Dummy custom operation"""
             num_wires = 1
             num_params = 1
@@ -394,7 +391,7 @@ def test_no_wires_passed(self):
         """Test exception raised if no wires are passed"""
         self.logTestName()
 
-        class DummyOp(oo.Operation):
+        class DummyOp(qml.operation.Operation):
             r"""Dummy custom operation"""
             num_wires = 1
             num_params = 1
@@ -408,7 +405,7 @@ def test_wire_passed_positionally(self):
         """Test exception raised if wire is passed as a positional arg"""
         self.logTestName()
 
-        class DummyOp(oo.Operation):
+        class DummyOp(qml.operation.Operation):
             r"""Dummy custom operation"""
             num_wires = 1
             num_params = 1
@@ -422,7 +419,7 @@ def test_observable_return_type_none(self):
         """Check that the return_type of an observable is initially None"""
         self.logTestName()
 
-        class DummyObserv(oo.Observable):
+        class DummyObserv(qml.operation.Observable):
             r"""Dummy custom observable"""
             num_wires = 1
             num_params = 1
@@ -433,7 +430,7 @@ class DummyObserv(oo.Observable):
 
 
 if __name__ == '__main__':
-    print('Testing PennyLane version ' + pennylane.version() + ', Operation class.')
+    print('Testing PennyLane version ' + qml.version() + ', Operation class.')
     # run the tests in this file
     suite = unittest.TestSuite()
     for t in (BasicTest, DeveloperTests):