Repository: rigetticomputing/pyquil (python)

Issue:
Add __len__ to program objects
Add __len__ method to program objects so that users can do `len(program)`.

Note there is a bit of difficulty here in that the program has to be synthesized first, perhaps we could start by just counting the number of lines in .out().

Pull request:
Add __len__ to InstructionGroup
Fixes #162.

This implementation counts the number of elements in synthesize(), and makes len() available for both InstructionGroup and Program.

Possible consideration - returning a more useful error message on infinite recursion by catching `RecursionError`.

Patch:
diff --git a/pyquil/quilbase.py b/pyquil/quilbase.py
index 82aad3c..ff40289 100644
--- a/pyquil/quilbase.py
+++ b/pyquil/quilbase.py
@@ -254,6 +254,9 @@ class InstructionGroup(QuilAction):
 
         return synthesized
 
+    def __len__(self):
+        return len(self.synthesize())
+
     def __str__(self):
         return self.out()
 


Test patch:
diff --git a/pyquil/tests/test_quil.py b/pyquil/tests/test_quil.py
index 482f374..e4dfefb 100644
--- a/pyquil/tests/test_quil.py
+++ b/pyquil/tests/test_quil.py
@@ -108,6 +108,23 @@ def test_program_pop():
     assert Program(instruction).out() == "X 1\n"
 
 
+def test_len_zero():
+    prog = Program()
+    assert len(prog) == 0
+
+
+def test_len_one():
+    prog = Program(X(0))
+    assert len(prog) == 1
+
+
+def test_len_nested():
+    p = Program(H(0)).measure(0, 0)
+    q = Program(H(0), CNOT(0, 1))
+    p.if_then(0, q)
+    assert len(p) == 8
+
+
 def test_plus_operator():
     p = Program()
     p += H(0)