ob-python
is also peculiar. Try this:
#+name: test-data
#+begin_src octave :session test_case :results value
a =[ 1 2; 3 4; 5 6];
ans = a
#+END_SRC
#+RESULTS: test-data
| 1 | 2 |
| 3 | 4 |
| 5 | 6 |
#+NAME: octave-to-python
#+BEGIN_SRC python :var x=test-data :results value
return len(x)
#+END_SRC
#+RESULTS: octave-to-python
3
ob-python
's peculiarity is the different way it treats :results value
blocks and :results output
blocks: when you specify :results value
(which you also get by default if you don't specify anything), then ob-python
wraps the source block code in a function, calls the function, gets the result and fills in the #+RESULTS
block. That's why you need to have a return
in the source block: without it, nothing is returned (actually what is returned is the None
object, so that's what you get).
The trouble is that if you decide that you want :results output
instead,
ob-python
decides that in this case, it is not going to wrap the code in a function and if you try to execute it, you get a syntax error: SyntaxError: 'return' outside function
. So the same code block gives different results, depending on whether you have specified :results value
or :results output
- that in itself is perhaps not surprising, since there is no reason that that a result value should be the same as what is printed out, but depending on the code, in one case you get what you expect and in the other case you get a syntax error, because ob-python
treats those two cases very differently. E.g.:
#+begin_src python :var a=3 :var b=4
sum = a + b
print("The sum is:", sum)
return sum
#+end_src
#+RESULTS:
: 7
#+begin_src python :var a=3 :var b=4 :results output
sum = a + b
print("The sum is:", sum)
return sum
#+end_src
#+RESULTS:
In the first case (:results value
), the output of the print
disappears, and the value is 7
, so that's what the #+RESULS:
block shows. In the second case, the same code block but with :results output
specified, gives a syntax error: you have to get rid of the return sum
line in order for it to run without error, in which case the result is the output of the print
: The sum is 7
.
There are technical reasons for this inconsistency, but it is an inconsistency and it is surprising when you first encounter it.