Search code examples
emacsorg-mode

How to use variables from an org-mode source block in an inline source code?


I have a python source block that gets the number of variables (columns) and cases in a pandas' dataframe.

Minimal example:

#+begin_src python :exports none :session :results output
  df = pd.DataFrame({'a': [1, 2, 3],
                     'b': [4, 5, 6]})
  df_len_columns = len(df.columns)
  df_len_cases = len(df.index)
#+end_src

What I would like to do now is use the value of those variables in inline source code like this:

The number of variables is src_python{df_len_columns} and the number of cases is src_python{df_len_cases}.

But this throws the following error:

NameError: name 'df_len_columns' is not defined

Notice that I'm using the session argument :session thinking that it would be part of the same session and that it would work. I also search online extensively but couldn't find a solution to this particular question (most questions are about inline code for tables and inline code formatting).

Is there anyway to actually use these variables inline?


Solution

  • It looks like you need to tell the inline source code to refer to your session using a header argument:

    src_python[:session]{df_len_columns}
    

    The general form is src_<language>[<header arguments>]{<body>}. Possible header arguments are listed in the org manual: Specific Header Arguments.

    Note: The value is substituted when the org file is exported via org-export-dispatch.