Skip to content

Commit

Permalink
IPython displays a Hamiltonian's str representation instead of `r…
Browse files Browse the repository at this point in the history
…epr` (#2648)

* hamiltonian ipython_display

* Update doc/releases/changelog-dev.md

* Update pennylane/ops/qubit/hamiltonian.py

* black and docstring
  • Loading branch information
albi3ro authored Jun 1, 2022
1 parent e4d86eb commit 3fa7518
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
4 changes: 4 additions & 0 deletions doc/releases/changelog-dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,10 @@

<h3>Improvements</h3>

* IPython displays the `str` representation of a `Hamiltonian`, rather than the `repr`. This displays
more information about the object.
[(#2648)](https://github.com/PennyLaneAI/pennylane/pull/2648)

* The qchem openfermion-dependent tests are localized and collected in `tests.qchem.of_tests`. The
new module `test_structure` is created to collect the tests of the `qchem.structure` module in
one place and remove their dependency to openfermion.
Expand Down
6 changes: 6 additions & 0 deletions pennylane/ops/qubit/hamiltonian.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,12 @@ def __repr__(self):
# Constructor-call-like representation
return f"<Hamiltonian: terms={qml.math.shape(self.coeffs)[0]}, wires={self.wires.tolist()}>"

def _ipython_display_(self): # pragma: no-cover
"""Displays __str__ in ipython instead of __repr__
See https://ipython.readthedocs.io/en/stable/config/integrating.html
"""
print(self.__str__())

def _obs_data(self):
r"""Extracts the data from a Hamiltonian and serializes it in an order-independent fashion.
Expand Down
9 changes: 9 additions & 0 deletions tests/ops/qubit/test_hamiltonian.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
import numpy as np
import pytest

from unittest.mock import patch

import pennylane as qml
from pennylane import numpy as pnp

Expand Down Expand Up @@ -642,6 +644,13 @@ def test_hamiltonian_str(self, terms, string):
H = qml.Hamiltonian(*terms)
assert H.__str__() == string

@patch("builtins.print")
def test_hamiltonian_ipython_display(self, mock_print):
"""Test that the ipython_dipslay method prints __str__."""
H = 1.0 * qml.PauliX(0)
H._ipython_display_()
mock_print.assert_called_with(str(H))

@pytest.mark.parametrize("terms, string", zip(valid_hamiltonians, valid_hamiltonians_repr))
def test_hamiltonian_repr(self, terms, string):
"""Tests that the __repr__ function for printing is correct"""
Expand Down

0 comments on commit 3fa7518

Please sign in to comment.