qiskit: Using a numpy integer type as an index for a QuantumRegister fails

Information

  • Qiskit Terra version: 0.11.1
  • Python version: 3.7.6
  • Operating system: Ubuntu 18.04.4 LTS

What is the current behavior?

An error is raised:

File "/lib/python3.7/site-packages/qiskit/circuit/register.py", line 90, in __getitem__
    raise CircuitError("expected integer or slice index into register")
qiskit.circuit.exceptions.CircuitError: 'expected integer or slice index into register'

Steps to reproduce the problem

from qiskit import QuantumRegister
import numpy as np
qr = QuantumRegister(3)
qubit_index = np.int64(0)
qubit = qr[qubit_index]

What is the expected behavior?

Since numpy is used extensively in scientific programming, the type checking should not be as strict.

Suggested solutions

Change line 89 of register.py from:

if not isinstance(key, (int, slice, list)):

to

if not isinstance(key, (int, slice, list, np.integer)):

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 16 (13 by maintainers)

Most upvoted comments

Hi, I am keen to contribute to solving this as my first issue. Can I work on this?

isinstance(foo, numbers.Integral) and 0 <= foo < len(self) should cover those cases.

Agree, in general, try/catch is more pythonic (and would simplify implementation), but would leave gaps for users who are new to python. e.g. int(3.5) == 3.

Everything should be a numbers.Number

Great, I’ll get round to it over the next few days! Looking forward to my first PR