Skip to content

Commit

Permalink
Cache _single_string to fix __repr__ and _repr_html__ issue
Browse files Browse the repository at this point in the history
  • Loading branch information
enavarro51 committed Jul 19, 2023
1 parent dba3b50 commit a4ff5f0
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions qiskit/visualization/circuit/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,11 @@ def __init__(

self._nest_depth = 0 # nesting depth for control flow ops

# Because jupyter calls both __repr__ and __repr_html__ for some backends,
# the entire drawer can be run twice which can result in different output
# for different backends. This var caches the output so the drawer only runs once.
self._single_string = ""

def __str__(self):
return self.single_string()

Expand All @@ -767,25 +772,30 @@ def _repr_html_(self):
)

def __repr__(self):
if ("ipykernel" in sys.modules) and ("spyder" not in sys.modules):
return ""
return self.single_string()

def single_string(self):
"""Creates a long string with the ascii art.
Returns:
str: The lines joined by a newline (``\\n``)
"""
if self._single_string:
return self._single_string
try:
return "\n".join(self.lines()).encode(self.encoding).decode(self.encoding)
self._single_string = (
"\n".join(self.lines()).encode(self.encoding).decode(self.encoding)
)
except (UnicodeEncodeError, UnicodeDecodeError):
warn(
"The encoding %s has a limited charset. Consider a different encoding in your "
"environment. UTF-8 is being used instead" % self.encoding,
RuntimeWarning,
)
self.encoding = "utf-8"
return "\n".join(self.lines()).encode(self.encoding).decode(self.encoding)
self._single_string = (
"\n".join(self.lines()).encode(self.encoding).decode(self.encoding)
)
return self._single_string

def dump(self, filename, encoding=None):
"""Dumps the ascii art in the file.
Expand Down

0 comments on commit a4ff5f0

Please sign in to comment.