[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: “Literate” python?
From: |
Berry, Charles |
Subject: |
Re: “Literate” python? |
Date: |
Fri, 29 Nov 2019 19:22:54 +0000 |
> On Nov 29, 2019, at 9:54 AM, Norman Walsh <address@hidden> wrote:
>
> Hi,
>
> I’ve seen a couple of pointers recently to using Org mode and tangle
> to write more literate Emacs configurations. I use Org+babel all the
> time to write “interactive” documents, so I thought I’d try out tangle
> from Org.
>
> I didn’t want to start with something as comlicated as my Emacs
> config :-) so I figured I’d kick the tires with a small python
> program. That did not end well.
>
> Consider:
>
> #+TITLE: Python literate programming
> #+OPTIONS: html-postamble:nil
>
> It starts off as a completely standard Python3 program.
>
> ---%<------------------------------------------------------
> #+BEGIN_SRC python :tangle yes :weave no
> #!/usr/bin/env python3
>
> #+END_SRC
>
> It defines ~a~.
>
> #+BEGIN_SRC python :tangle yes
> def a():
> print("a")
>
>
> #+END_SRC
>
> And ~b~.
>
> #+BEGIN_SRC python :tangle yes
> def b():
> print("b")
>
>
> #+END_SRC
>
> Now ~c~ is a little more complicated:
>
> #+BEGIN_SRC python :tangle yes
> def c():
> print("c")
> #+END_SRC
>
> Not only does ~c~ print “c”, it calls ~a()~ and ~b()~.
>
> #+BEGIN_SRC python :tangle yes
> b()
> a()
> #+END_SRC
>
> Finally, make it importable. Not that you’d want to.
>
> #+BEGIN_SRC python :tangle yes
> if __name__ == "__main__":
> main()
> #+END_SRC
> --->%------------------------------------------------------
>
> That’s the script. It weaves into HTML more-or-less ok (there’s a
> weird black box at the front of indented lines, but I can come back to
> that later).
>
> It’s a complete mess when tangled.
>
> The extra blank lines between functions (to make pylint happy with
> some PEP guideline) have disappeared. I guess I could live with that,
> but the complete failure to preserve indention in the penultimate code
> block is a show stopper:
[results of tangling deleted]
A couple of things might help.
First, use the :noweb-ref argument to mark each of the code blocks you wish to
tangle.
Say `:noweb-ref tangleyes'. Or some more evocative name.
Remove the `:tangle yes' from each of those. Then, add a code block that has
only `<<tangleyes>>' in it and tangle it.
#+begin_src python :noweb yes :tangle yes
<<tangleyes>>
#+end_src
The remaining problem (as you will see) is the indentation. Fix this by adding
the `-i' flag to the penultimate code block, viz.
#+BEGIN_SRC python -i :noweb-ref tangleyes
b()
a()
#+END_SRC
See 12.6 Literal Examples and 15.10 Noweb Reference Syntax in the manual.
HTH,
Chuck