{"title":"Casthoughts","link":[{"@attributes":{"href":"https:\/\/tacaswell.github.io\/","rel":"alternate"}},{"@attributes":{"href":"https:\/\/tacaswell.github.io\/feeds\/all.atom.xml","rel":"self"}}],"id":"https:\/\/tacaswell.github.io\/","updated":"2022-11-25T22:00:00-05:00","subtitle":"Software and such","entry":[{"title":"Reflowing Axes","link":{"@attributes":{"href":"https:\/\/tacaswell.github.io\/dynamic-axes-count.html","rel":"alternate"}},"published":"2022-11-25T22:00:00-05:00","updated":"2022-11-25T22:00:00-05:00","author":{"name":"Thomas A Caswell"},"id":"tag:tacaswell.github.io,2022-11-25:\/dynamic-axes-count.html","summary":"<p>Dynamically adding Axes to a Figure<\/p>","content":"<p>At the prompting of a user on Matplotlib&rsquo;s gitter channel I wrote the following\nexample:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">matplotlib.pyplot<\/span><span class=\"w\"> <\/span><span class=\"k\">as<\/span><span class=\"w\"> <\/span><span class=\"nn\">plt<\/span>\n<span class=\"kn\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">numpy<\/span><span class=\"w\"> <\/span><span class=\"k\">as<\/span><span class=\"w\"> <\/span><span class=\"nn\">np<\/span>\n<span class=\"kn\">from<\/span><span class=\"w\"> <\/span><span class=\"nn\">itertools<\/span><span class=\"w\"> <\/span><span class=\"kn\">import<\/span> <span class=\"n\">count<\/span>\n<span class=\"kn\">from<\/span><span class=\"w\"> <\/span><span class=\"nn\">matplotlib.gridspec<\/span><span class=\"w\"> <\/span><span class=\"kn\">import<\/span> <span class=\"n\">GridSpec<\/span>\n\n\n<span class=\"k\">def<\/span><span class=\"w\"> <\/span><span class=\"nf\">reflow_gen<\/span><span class=\"p\">(<\/span><span class=\"n\">fig<\/span><span class=\"p\">):<\/span>\n    <span class=\"c1\"># we own this figure now so clear it<\/span>\n    <span class=\"n\">fig<\/span><span class=\"o\">.<\/span><span class=\"n\">clf<\/span><span class=\"p\">()<\/span>\n    <span class=\"c1\"># running count of the number of axes<\/span>\n    <span class=\"n\">axcount<\/span> <span class=\"o\">=<\/span> <span class=\"n\">count<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"c1\"># the shape of the grid<\/span>\n    <span class=\"n\">row_guess<\/span> <span class=\"o\">=<\/span> <span class=\"n\">col_guess<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">0<\/span>\n    <span class=\"c1\"># the current GridSpec object<\/span>\n    <span class=\"n\">gs<\/span> <span class=\"o\">=<\/span> <span class=\"kc\">None<\/span>\n\n    <span class=\"c1\"># we are a generator, so loop forever<\/span>\n    <span class=\"k\">while<\/span> <span class=\"kc\">True<\/span><span class=\"p\">:<\/span>\n        <span class=\"c1\"># what number is this Axes?<\/span>\n        <span class=\"n\">j<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">next<\/span><span class=\"p\">(<\/span><span class=\"n\">axcount<\/span><span class=\"p\">)<\/span>\n        <span class=\"c1\"># do we need to re-flow?<\/span>\n        <span class=\"k\">if<\/span> <span class=\"n\">j<\/span> <span class=\"o\">&gt;<\/span> <span class=\"n\">row_guess<\/span> <span class=\"o\">*<\/span> <span class=\"n\">col_guess<\/span><span class=\"p\">:<\/span>\n            <span class=\"c1\"># Find the smallest square that will work<\/span>\n            <span class=\"n\">col_guess<\/span> <span class=\"o\">=<\/span> <span class=\"n\">row_guess<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">int<\/span><span class=\"p\">(<\/span><span class=\"n\">np<\/span><span class=\"o\">.<\/span><span class=\"n\">ceil<\/span><span class=\"p\">(<\/span><span class=\"n\">np<\/span><span class=\"o\">.<\/span><span class=\"n\">sqrt<\/span><span class=\"p\">(<\/span><span class=\"n\">j<\/span><span class=\"p\">)))<\/span>\n            <span class=\"c1\"># and then drop fully empty rows<\/span>\n            <span class=\"k\">for<\/span> <span class=\"n\">k<\/span> <span class=\"ow\">in<\/span> <span class=\"nb\">range<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"n\">row_guess<\/span><span class=\"p\">):<\/span>\n                <span class=\"k\">if<\/span> <span class=\"p\">(<\/span><span class=\"n\">row_guess<\/span> <span class=\"o\">-<\/span> <span class=\"mi\">1<\/span><span class=\"p\">)<\/span> <span class=\"o\">*<\/span> <span class=\"n\">col_guess<\/span> <span class=\"o\">&lt;<\/span> <span class=\"n\">j<\/span><span class=\"p\">:<\/span>\n                    <span class=\"k\">break<\/span>\n                <span class=\"k\">else<\/span><span class=\"p\">:<\/span>\n                    <span class=\"n\">row_guess<\/span> <span class=\"o\">-=<\/span> <span class=\"mi\">1<\/span>\n\n            <span class=\"c1\"># Create the new gridspec object<\/span>\n            <span class=\"n\">gs<\/span> <span class=\"o\">=<\/span> <span class=\"n\">GridSpec<\/span><span class=\"p\">(<\/span><span class=\"n\">row_guess<\/span><span class=\"p\">,<\/span> <span class=\"n\">col_guess<\/span><span class=\"p\">,<\/span> <span class=\"n\">figure<\/span><span class=\"o\">=<\/span><span class=\"n\">fig<\/span><span class=\"p\">)<\/span>\n\n            <span class=\"c1\"># for each of the axes, adjust it to use the new gridspec<\/span>\n            <span class=\"k\">for<\/span> <span class=\"n\">n<\/span><span class=\"p\">,<\/span> <span class=\"n\">ax<\/span> <span class=\"ow\">in<\/span> <span class=\"nb\">enumerate<\/span><span class=\"p\">(<\/span><span class=\"n\">fig<\/span><span class=\"o\">.<\/span><span class=\"n\">axes<\/span><span class=\"p\">):<\/span>\n                <span class=\"n\">ax<\/span><span class=\"o\">.<\/span><span class=\"n\">set_subplotspec<\/span><span class=\"p\">(<\/span><span class=\"n\">gs<\/span><span class=\"p\">[<\/span><span class=\"o\">*<\/span><span class=\"n\">np<\/span><span class=\"o\">.<\/span><span class=\"n\">unravel_index<\/span><span class=\"p\">(<\/span><span class=\"n\">n<\/span><span class=\"p\">,<\/span> <span class=\"p\">(<\/span><span class=\"n\">row_guess<\/span><span class=\"p\">,<\/span> <span class=\"n\">col_guess<\/span><span class=\"p\">))])<\/span>\n            <span class=\"c1\"># resize the figure to have ~ 3:4 ratio and keep the Axes fixed<\/span>\n            <span class=\"n\">fig<\/span><span class=\"o\">.<\/span><span class=\"n\">set_size_inches<\/span><span class=\"p\">(<\/span><span class=\"n\">col_guess<\/span> <span class=\"o\">*<\/span> <span class=\"mi\">4<\/span><span class=\"p\">,<\/span> <span class=\"n\">row_guess<\/span> <span class=\"o\">*<\/span> <span class=\"mi\">3<\/span><span class=\"p\">)<\/span>\n\n        <span class=\"c1\"># Add the new axes to the Figure at the next open space<\/span>\n        <span class=\"n\">new_ax<\/span> <span class=\"o\">=<\/span> <span class=\"n\">fig<\/span><span class=\"o\">.<\/span><span class=\"n\">add_subplot<\/span><span class=\"p\">(<\/span><span class=\"n\">gs<\/span><span class=\"p\">[<\/span><span class=\"o\">*<\/span><span class=\"n\">np<\/span><span class=\"o\">.<\/span><span class=\"n\">unravel_index<\/span><span class=\"p\">(<\/span><span class=\"n\">j<\/span> <span class=\"o\">-<\/span> <span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"p\">(<\/span><span class=\"n\">row_guess<\/span><span class=\"p\">,<\/span> <span class=\"n\">col_guess<\/span><span class=\"p\">))])<\/span>\n\n        <span class=\"c1\"># hand the Axes back to the user<\/span>\n        <span class=\"k\">yield<\/span> <span class=\"n\">new_ax<\/span>\n\n<span class=\"c1\"># make a Figure<\/span>\n<span class=\"n\">fig<\/span> <span class=\"o\">=<\/span> <span class=\"n\">plt<\/span><span class=\"o\">.<\/span><span class=\"n\">figure<\/span><span class=\"p\">(<\/span><span class=\"n\">layout<\/span><span class=\"o\">=<\/span><span class=\"s1\">&#39;constrained&#39;<\/span><span class=\"p\">)<\/span>\n<span class=\"c1\"># set up the generator<\/span>\n<span class=\"n\">ax_gen<\/span> <span class=\"o\">=<\/span> <span class=\"n\">reflow_gen<\/span><span class=\"p\">(<\/span><span class=\"n\">fig<\/span><span class=\"p\">)<\/span>\n<span class=\"k\">for<\/span> <span class=\"n\">j<\/span> <span class=\"ow\">in<\/span> <span class=\"nb\">range<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">):<\/span>\n    <span class=\"c1\"># get an Axes<\/span>\n    <span class=\"n\">ax<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">next<\/span><span class=\"p\">(<\/span><span class=\"n\">ax_gen<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">ax<\/span><span class=\"o\">.<\/span><span class=\"n\">set_title<\/span><span class=\"p\">(<\/span><span class=\"sa\">f<\/span><span class=\"s1\">&#39;Axes <\/span><span class=\"si\">{<\/span><span class=\"n\">j<\/span><span class=\"si\">}<\/span><span class=\"s1\">&#39;<\/span><span class=\"p\">)<\/span>\n    <span class=\"c1\"># fig.savefig(f&#39;dynamic_axes_figs-axes_{j}.svg&#39;)<\/span>\n<span class=\"n\">plt<\/span><span class=\"o\">.<\/span><span class=\"n\">show<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p><strong>1 axes (1x1)<\/strong><\/p>\n<p><img alt=\"Figure with 1 Axes added\" src=\"\/images\/dynamic_axes_figs-axes_0.svg\" title=\"1 Axes\"><\/p>\n<p><strong>2 axes (2x1)<\/strong><\/p>\n<p><img alt=\"Figure with 2 Axes added\" src=\"\/images\/dynamic_axes_figs-axes_1.svg\" title=\"2 Axes\"><\/p>\n<p><strong>3 axes (2x2)<\/strong><\/p>\n<p><img alt=\"Figure with 3 Axes added\" src=\"\/images\/dynamic_axes_figs-axes_2.svg\" title=\"3 Axes\"><\/p>\n<p><strong>4 axes (2x2)<\/strong><\/p>\n<p><img alt=\"Figure with 4 Axes added\" src=\"\/images\/dynamic_axes_figs-axes_3.svg\" title=\"4 Axes\"><\/p>\n<p><strong>5 axes (3x2)<\/strong><\/p>\n<p><img alt=\"Figure with 5 Axes added\" src=\"\/images\/dynamic_axes_figs-axes_4.svg\" title=\"5 Axes\"><\/p>\n<p>and so on up to as many <em>Axes<\/em> as you want to add.  Note that the Figure is\ngetting bigger as more Axes are added so if using this interactively the window\nwill grow.<\/p>\n<p>I am not sure that this is general enough to add to Matplotlib, but it is a\ncute example of how generators can be useful.  One concern with this code is\nthat the generator will keep the <em>Figure<\/em> object alive which may complicate\nresource management.  There are also some questions for me about what the API\nshould be.  As written the resizing and target aspect ratio behavior is fixed,\nI think it is reasonable for users to be able to control both.  Additional, the\nscheme for growing the grid and selecting which slots to fill at a given grid\nsize and fill factor could be elaborated.  It might also be interesting to\npromote the generator to a full <a href=\"https:\/\/tacaswell.github.io\/coroutines-i.html\">generator\nco-routine<\/a> to be able to pass arguments the Axes\ncreation step (to set projections and such).<\/p>","category":[{"@attributes":{"term":"Matplotlib"}},{"@attributes":{"term":"Matplotlib generator"}}]},{"title":"Coroutines (practical)","link":{"@attributes":{"href":"https:\/\/tacaswell.github.io\/coroutines-i.html","rel":"alternate"}},"published":"2022-10-14T17:25:00-04:00","updated":"2022-10-15T11:15:00-04:00","author":{"name":"Thomas A Caswell"},"id":"tag:tacaswell.github.io,2022-10-14:\/coroutines-i.html","summary":"<p>So you have been handed a generator co-routine&hellip;<\/p>","content":"<p>This is a explanation of how to practically work with generator coroutines in\nPython.  If you are willing to accept the rules laid out in this (not so) short\nguide as empirical observations then you should be able to productively work\nwith generator co-routines.  In a future post I intend to dive into the &ldquo;why&rdquo;\n(and the &ldquo;why this makes sense&rdquo;), but this is the pragmatic view.<\/p>\n<p>Generator coroutines in Python have two bi-directional communication channels<\/p>\n<ol>\n<li>data <code>yield<\/code> \/ <code>send()<\/code><\/li>\n<li>exceptions via <code>raise<\/code> \/ <code>throw()<\/code><\/li>\n<\/ol>\n<p>and two unidirectional channels<\/p>\n<ol>\n<li>data via <code>return<\/code><\/li>\n<li><code>close()<\/code> to exit the coroutine immediately<\/li>\n<\/ol>\n<p>Another way to look at this is generator co-routines have two &ldquo;happy path&rdquo;\ncommunication channels:<\/p>\n<ol>\n<li>data <code>yield<\/code> \/ <code>send()<\/code><\/li>\n<li>data via <code>return<\/code><\/li>\n<\/ol>\n<p>and two &ldquo;sad path&rdquo; communication channels:<\/p>\n<ol>\n<li>exceptions via <code>raise<\/code> \/ <code>throw()<\/code><\/li>\n<li><code>close()<\/code> to exit the coroutine immediately<\/li>\n<\/ol>\n<p>Each of these channels has a different purpose and without one of them\nco-routines would be incomplete.  You may not need to (explicitly) use all of\nthese channels in any given application.<\/p>\n<h2 id=\"yield-send-data-channel\"><code>yield<\/code> \/ <code>send()<\/code> data channel<\/h2>\n<p>The first half of this channel is <code>yield<\/code> which will (as the name suggests)\nyield value out of the coroutine.  If we only use the <code>yield<\/code> the we have a\n&ldquo;generator function&rdquo;, for example if we write<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span><span class=\"w\"> <\/span><span class=\"nf\">my_gen<\/span><span class=\"p\">():<\/span>\n    <span class=\"k\">yield<\/span> <span class=\"s1\">&#39;a&#39;<\/span>\n    <span class=\"k\">yield<\/span> <span class=\"s1\">&#39;b&#39;<\/span>\n    <span class=\"k\">yield<\/span> <span class=\"s1\">&#39;c&#39;<\/span>\n<\/code><\/pre><\/div>\n\n<p>which we can then use with the iteration protocol as:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"nb\">list<\/span><span class=\"p\">(<\/span><span class=\"n\">my_gen<\/span><span class=\"p\">())<\/span>\n<span class=\"p\">[<\/span><span class=\"s1\">&#39;a&#39;<\/span><span class=\"p\">,<\/span> <span class=\"s1\">&#39;b&#39;<\/span><span class=\"p\">,<\/span> <span class=\"s1\">&#39;c&#39;<\/span><span class=\"p\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>More explicitly, what <code>list<\/code> (or a <code>for<\/code> loop) is doing under the hood is:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">g<\/span> <span class=\"o\">=<\/span> <span class=\"n\">my_gen<\/span><span class=\"p\">()<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"nb\">next<\/span><span class=\"p\">(<\/span><span class=\"n\">g<\/span><span class=\"p\">)<\/span>\n<span class=\"s1\">&#39;a&#39;<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"nb\">next<\/span><span class=\"p\">(<\/span><span class=\"n\">g<\/span><span class=\"p\">)<\/span>\n<span class=\"s1\">&#39;b&#39;<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"nb\">next<\/span><span class=\"p\">(<\/span><span class=\"n\">g<\/span><span class=\"p\">)<\/span>\n<span class=\"s1\">&#39;c&#39;<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"nb\">next<\/span><span class=\"p\">(<\/span><span class=\"n\">g<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">Traceback<\/span> <span class=\"p\">(<\/span><span class=\"n\">most<\/span> <span class=\"n\">recent<\/span> <span class=\"n\">call<\/span> <span class=\"n\">last<\/span><span class=\"p\">):<\/span>\n  <span class=\"n\">File<\/span> <span class=\"s2\">&quot;&lt;stdin&gt;&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">line<\/span> <span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"ow\">in<\/span> <span class=\"o\">&lt;<\/span><span class=\"n\">module<\/span><span class=\"o\">&gt;<\/span>\n<span class=\"ne\">StopIteration<\/span>\n<\/code><\/pre><\/div>\n\n<p>The way that the generator communicates that it is exhausted is by raising the\n<code>StopIteration<\/code>\n<a href=\"https:\/\/docs.python.org\/3\/library\/exceptions.html#StopIteration\">exception<\/a>.\nWe will come back to the raised Exception object in a bit.<\/p>\n<p>Using <code>yield<\/code> we can get information <em>out<\/em> of generator coroutine, to get data\ninto the generator coroutine we need to capture a left-hand side of the <code>yield<\/code>\nas<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span><span class=\"w\"> <\/span><span class=\"nf\">my_gen<\/span><span class=\"p\">():<\/span>\n    <span class=\"n\">in1<\/span> <span class=\"o\">=<\/span> <span class=\"k\">yield<\/span> <span class=\"s1\">&#39;a&#39;<\/span>\n    <span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"sa\">f<\/span><span class=\"s1\">&#39;got <\/span><span class=\"si\">{<\/span><span class=\"n\">in1<\/span><span class=\"si\">!r}<\/span><span class=\"s1\">&#39;<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">in2<\/span> <span class=\"o\">=<\/span> <span class=\"k\">yield<\/span> <span class=\"s1\">&#39;b&#39;<\/span>\n    <span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"sa\">f<\/span><span class=\"s1\">&#39;got <\/span><span class=\"si\">{<\/span><span class=\"n\">in2<\/span><span class=\"si\">!r}<\/span><span class=\"s1\">&#39;<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>If we pass that to <code>list<\/code> we see:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;<\/span> <span class=\"nb\">list<\/span><span class=\"p\">(<\/span><span class=\"n\">my_gen<\/span><span class=\"p\">())<\/span>\n<span class=\"n\">got<\/span> <span class=\"kc\">None<\/span>\n<span class=\"n\">got<\/span> <span class=\"kc\">None<\/span>\n<span class=\"p\">[<\/span><span class=\"s1\">&#39;a&#39;<\/span><span class=\"p\">,<\/span> <span class=\"s1\">&#39;b&#39;<\/span><span class=\"p\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>What this (and <code>next<\/code>) is doing under the hood is<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">g<\/span> <span class=\"o\">=<\/span> <span class=\"n\">my_gen<\/span><span class=\"p\">()<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"kc\">None<\/span><span class=\"p\">)<\/span>\n<span class=\"s1\">&#39;a&#39;<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"kc\">None<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">got<\/span> <span class=\"kc\">None<\/span>\n<span class=\"s1\">&#39;b&#39;<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"kc\">None<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">got<\/span> <span class=\"kc\">None<\/span>\n<span class=\"n\">Traceback<\/span> <span class=\"p\">(<\/span><span class=\"n\">most<\/span> <span class=\"n\">recent<\/span> <span class=\"n\">call<\/span> <span class=\"n\">last<\/span><span class=\"p\">):<\/span>\n  <span class=\"n\">File<\/span> <span class=\"s2\">&quot;&lt;stdin&gt;&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">line<\/span> <span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"ow\">in<\/span> <span class=\"o\">&lt;<\/span><span class=\"n\">module<\/span><span class=\"o\">&gt;<\/span>\n<span class=\"ne\">StopIteration<\/span>\n<\/code><\/pre><\/div>\n\n<p>The sequence is:<\/p>\n<ol>\n<li>Create the generator.  At this point no code has run yet.<\/li>\n<li>The first <code>.send()<\/code> runs the coroutine up to the first <code>yield<\/code> and sends the\n   right hand side out.  The value of the first <code>.send<\/code> <em>must<\/em> be <code>None<\/code>\n   because there is no way to access the value passed in.<\/li>\n<li>The coroutine is suspended until the next <code>send()<\/code>.  The value pass to the\n   second <code>send()<\/code> is assigned to the left hand side of the <code>yield<\/code> expression.<\/li>\n<li>The coroutine runs until the next <code>yield<\/code> and sends out the right hand side.  We\n   then go back to step 3 until there are no more <code>yield<\/code> expressions in the coroutine.<\/li>\n<li>when the coroutine returns Python will raise the <code>StopIteration<\/code> exception\n   for us.<\/li>\n<\/ol>\n<p>To see this more clearly, re-running the above code but sending in diffrent\nvalues at each step:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">g<\/span> <span class=\"o\">=<\/span> <span class=\"n\">my_gen<\/span><span class=\"p\">()<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"kc\">None<\/span><span class=\"p\">)<\/span>\n<span class=\"s1\">&#39;a&#39;<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;step 1&#39;<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">got<\/span> <span class=\"s1\">&#39;step 1&#39;<\/span>\n<span class=\"s1\">&#39;b&#39;<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;step 2&#39;<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">got<\/span> <span class=\"s1\">&#39;step 2&#39;<\/span>\n<span class=\"n\">Traceback<\/span> <span class=\"p\">(<\/span><span class=\"n\">most<\/span> <span class=\"n\">recent<\/span> <span class=\"n\">call<\/span> <span class=\"n\">last<\/span><span class=\"p\">):<\/span>\n  <span class=\"n\">File<\/span> <span class=\"s2\">&quot;&lt;stdin&gt;&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">line<\/span> <span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"ow\">in<\/span> <span class=\"o\">&lt;<\/span><span class=\"n\">module<\/span><span class=\"o\">&gt;<\/span>\n<span class=\"ne\">StopIteration<\/span>\n<\/code><\/pre><\/div>\n\n<h2 id=\"return-data-channel\"><code>return<\/code> data channel<\/h2>\n<p>So far we have not used <code>return<\/code> and relying on the implicit <code>return None<\/code> that\nPython provides.  As with any Python function we put a <code>return<\/code> in our\ncoroutine:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span><span class=\"w\"> <\/span><span class=\"nf\">my_gen<\/span><span class=\"p\">():<\/span>\n    <span class=\"n\">in1<\/span> <span class=\"o\">=<\/span> <span class=\"k\">yield<\/span> <span class=\"s1\">&#39;a&#39;<\/span>\n    <span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"sa\">f<\/span><span class=\"s1\">&#39;got <\/span><span class=\"si\">{<\/span><span class=\"n\">in1<\/span><span class=\"si\">!r}<\/span><span class=\"s1\">&#39;<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">in2<\/span> <span class=\"o\">=<\/span> <span class=\"k\">yield<\/span> <span class=\"s1\">&#39;b&#39;<\/span>\n    <span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"sa\">f<\/span><span class=\"s1\">&#39;got <\/span><span class=\"si\">{<\/span><span class=\"n\">in2<\/span><span class=\"si\">!r}<\/span><span class=\"s1\">&#39;<\/span><span class=\"p\">)<\/span>\n    <span class=\"k\">return<\/span> <span class=\"s1\">&#39;Done!&#39;<\/span>\n<\/code><\/pre><\/div>\n\n<p>However, this raise the question of how do we get to the returned value?  It\ncan not come back as the return from <code>.send()<\/code> as that is where the <code>yield<\/code>\nvalues are carried.  Instead the value is carried on the <code>StopIteration<\/code>\nexception that is raised when the iterator is exhausted.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">g<\/span> <span class=\"o\">=<\/span> <span class=\"n\">my_gen<\/span><span class=\"p\">()<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"kc\">None<\/span><span class=\"p\">)<\/span>\n<span class=\"s1\">&#39;a&#39;<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;step 1&#39;<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">got<\/span> <span class=\"s1\">&#39;step 1&#39;<\/span>\n<span class=\"s1\">&#39;b&#39;<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">g<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;step 2&#39;<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">got<\/span> <span class=\"s1\">&#39;step 2&#39;<\/span>\n<span class=\"n\">Traceback<\/span> <span class=\"p\">(<\/span><span class=\"n\">most<\/span> <span class=\"n\">recent<\/span> <span class=\"n\">call<\/span> <span class=\"n\">last<\/span><span class=\"p\">):<\/span>\n  <span class=\"n\">File<\/span> <span class=\"s2\">&quot;&lt;stdin&gt;&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">line<\/span> <span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"ow\">in<\/span> <span class=\"o\">&lt;<\/span><span class=\"n\">module<\/span><span class=\"o\">&gt;<\/span>\n<span class=\"ne\">StopIteration<\/span><span class=\"p\">:<\/span> <span class=\"n\">Done<\/span><span class=\"err\">!<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>To get the the value we need to catch the <code>StopIteration<\/code>\nand access <code>ex.value<\/code>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span> <span class=\"o\">=<\/span> <span class=\"n\">my_gen<\/span><span class=\"p\">()<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;yielded: &#39;<\/span><span class=\"p\">,<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"kc\">None<\/span><span class=\"p\">))<\/span>\n<span class=\"n\">yielded<\/span><span class=\"p\">:<\/span>  <span class=\"n\">a<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"k\">for<\/span> <span class=\"n\">j<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">count<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">):<\/span>\n<span class=\"o\">...<\/span>     <span class=\"k\">try<\/span><span class=\"p\">:<\/span>\n<span class=\"o\">...<\/span>         <span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;yielded: &#39;<\/span><span class=\"p\">,<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"sa\">f<\/span><span class=\"s1\">&#39;step <\/span><span class=\"si\">{<\/span><span class=\"n\">j<\/span><span class=\"si\">}<\/span><span class=\"s1\">&#39;<\/span><span class=\"p\">))<\/span>\n<span class=\"o\">...<\/span>     <span class=\"k\">except<\/span> <span class=\"ne\">StopIteration<\/span> <span class=\"k\">as<\/span> <span class=\"n\">ex<\/span><span class=\"p\">:<\/span>\n<span class=\"o\">...<\/span>         <span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"sa\">f<\/span><span class=\"s1\">&#39;Returned: <\/span><span class=\"si\">{<\/span><span class=\"n\">ex<\/span><span class=\"o\">.<\/span><span class=\"n\">value<\/span><span class=\"si\">}<\/span><span class=\"s1\">&#39;<\/span><span class=\"p\">)<\/span>\n<span class=\"o\">...<\/span>         <span class=\"k\">break<\/span>\n<span class=\"o\">...<\/span>\n<span class=\"n\">got<\/span> <span class=\"s1\">&#39;step 1&#39;<\/span>\n<span class=\"n\">yielded<\/span><span class=\"p\">:<\/span>  <span class=\"n\">b<\/span>\n<span class=\"n\">got<\/span> <span class=\"s1\">&#39;step 2&#39;<\/span>\n<span class=\"n\">Returned<\/span><span class=\"p\">:<\/span> <span class=\"n\">Done<\/span><span class=\"err\">!<\/span>\n<\/code><\/pre><\/div>\n\n<p>It may be tempting to try and raise your own <code>StopIteration<\/code> rather than\nreturning, however if you do Python will convert it to a <code>RuntimeError<\/code>.  This\nis because Python can not tell the difference between your intentionally\nraising <code>StopIteration<\/code> and something you have called unexpectedly raising\n<code>StopIteration<\/code>.  Pre <a href=\"https:\/\/peps.python.org\/pep-0479\/\">Python 3.5<\/a> the\n<code>StopIteration<\/code> would be raised to the outer caller which would be interpreted\nas the generator returning normally which in turn would mask bugs in very\nconfusing ways.<\/p>\n<h2 id=\"raise-throw-channel\"><code>raise<\/code> \/ <code>throw<\/code> channel<\/h2>\n<p>Like all Python we can use the standard exception raising and handling tools,\nhowever there are a couple a caveates.<\/p>\n<ol>\n<li>The co-routine must not raise <code>StopIteration<\/code> (as noted above)<\/li>\n<li>If you catch <code>GeneratorExit<\/code> the co-routine must return (see the section on\n   <code>close()<\/code> below).<\/li>\n<\/ol>\n<p>Any valid exception raised will inturn be raised from the call point of the\n<code>obj.send()<\/code> in the outer code, identically to how an exception called in a\nfunction will propogate to the call site.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"k\">def<\/span><span class=\"w\"> <\/span><span class=\"nf\">my_gen<\/span><span class=\"p\">(<\/span><span class=\"n\">N<\/span><span class=\"p\">):<\/span>\n<span class=\"o\">...<\/span>    <span class=\"k\">for<\/span> <span class=\"n\">j<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">count<\/span><span class=\"p\">():<\/span>\n<span class=\"o\">...<\/span>        <span class=\"k\">if<\/span> <span class=\"n\">j<\/span> <span class=\"o\">&gt;=<\/span> <span class=\"n\">N<\/span><span class=\"p\">:<\/span>\n<span class=\"o\">...<\/span>            <span class=\"k\">return<\/span> <span class=\"sa\">f<\/span><span class=\"s2\">&quot;Got <\/span><span class=\"si\">{<\/span><span class=\"n\">N<\/span><span class=\"si\">}<\/span><span class=\"s2\"> ints and are done&quot;<\/span>\n<span class=\"o\">...<\/span>        <span class=\"n\">a<\/span> <span class=\"o\">=<\/span> <span class=\"k\">yield<\/span> <span class=\"sa\">f<\/span><span class=\"s1\">&#39;<\/span><span class=\"si\">{<\/span><span class=\"n\">j<\/span><span class=\"si\">}<\/span><span class=\"s1\">\/<\/span><span class=\"si\">{<\/span><span class=\"n\">N<\/span><span class=\"si\">}<\/span><span class=\"s1\"> ints in a row&#39;<\/span>\n<span class=\"o\">...<\/span>        <span class=\"k\">if<\/span> <span class=\"ow\">not<\/span> <span class=\"nb\">isinstance<\/span><span class=\"p\">(<\/span><span class=\"n\">a<\/span><span class=\"p\">,<\/span> <span class=\"nb\">int<\/span><span class=\"p\">):<\/span>\n<span class=\"o\">...<\/span>            <span class=\"k\">raise<\/span> <span class=\"ne\">ValueError<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;We only take integers!&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"o\">...<\/span>\n<\/code><\/pre><\/div>\n\n<p>If we exhaust the &ldquo;happy path&rdquo; of this co-routine we see:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span> <span class=\"o\">=<\/span> <span class=\"n\">my_gen<\/span><span class=\"p\">(<\/span><span class=\"mi\">3<\/span><span class=\"p\">)<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"kc\">None<\/span><span class=\"p\">)<\/span>\n<span class=\"s1\">&#39;0\/3 ints in a row&#39;<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n<span class=\"s1\">&#39;1\/3 ints in a row&#39;<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"o\">-<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n<span class=\"s1\">&#39;2\/3 ints in a row&#39;<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"mi\">10<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">Traceback<\/span> <span class=\"p\">(<\/span><span class=\"n\">most<\/span> <span class=\"n\">recent<\/span> <span class=\"n\">call<\/span> <span class=\"n\">last<\/span><span class=\"p\">):<\/span>\n  <span class=\"n\">File<\/span> <span class=\"s2\">&quot;&lt;stdin&gt;&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">line<\/span> <span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"ow\">in<\/span> <span class=\"o\">&lt;<\/span><span class=\"n\">module<\/span><span class=\"o\">&gt;<\/span>\n<span class=\"ne\">StopIteration<\/span><span class=\"p\">:<\/span> <span class=\"n\">Got<\/span> <span class=\"mi\">3<\/span> <span class=\"n\">ints<\/span> <span class=\"ow\">and<\/span> <span class=\"n\">are<\/span> <span class=\"n\">done<\/span>\n<\/code><\/pre><\/div>\n\n<p>which raises <code>StopIteration<\/code> with the payload of a string as expected.  However, if we\nwere to send in not an integer<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span> <span class=\"o\">=<\/span> <span class=\"n\">my_gen<\/span><span class=\"p\">(<\/span><span class=\"mi\">3<\/span><span class=\"p\">)<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"kc\">None<\/span><span class=\"p\">)<\/span>\n<span class=\"s1\">&#39;0\/3 ints in a row&#39;<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">)<\/span>\n<span class=\"s1\">&#39;1\/3 ints in a row&#39;<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;aardvark&#39;<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">Traceback<\/span> <span class=\"p\">(<\/span><span class=\"n\">most<\/span> <span class=\"n\">recent<\/span> <span class=\"n\">call<\/span> <span class=\"n\">last<\/span><span class=\"p\">):<\/span>\n  <span class=\"n\">File<\/span> <span class=\"s2\">&quot;&lt;stdin&gt;&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">line<\/span> <span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"ow\">in<\/span> <span class=\"o\">&lt;<\/span><span class=\"n\">module<\/span><span class=\"o\">&gt;<\/span>\n  <span class=\"n\">File<\/span> <span class=\"s2\">&quot;&lt;stdin&gt;&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">line<\/span> <span class=\"mi\">7<\/span><span class=\"p\">,<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">my_gen<\/span>\n<span class=\"ne\">ValueError<\/span><span class=\"p\">:<\/span> <span class=\"n\">We<\/span> <span class=\"n\">only<\/span> <span class=\"n\">take<\/span> <span class=\"n\">integers<\/span><span class=\"err\">!<\/span>\n<\/code><\/pre><\/div>\n\n<p>However, if an unhandled exception is raised from a co-routine it is fully\nexhausted and subsequently sending in new values will immediantly raise\n<code>StopIteration<\/code>.<\/p>\n<p>Sometimes it is necessary to inject an exception into a co-routine, for example\nto let the co-routine know the outer code did not like the last yielded value.\nThis can be done with the <code>obj.throw<\/code> method which causes the passed\n<code>Exception<\/code> to be raised at the <code>yield<\/code>.  Within the co-routine we can use all\nof the standard exception handling tools of Python:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"k\">def<\/span><span class=\"w\"> <\/span><span class=\"nf\">my_gen<\/span><span class=\"p\">():<\/span>\n<span class=\"o\">...<\/span>    <span class=\"k\">for<\/span> <span class=\"n\">j<\/span> <span class=\"ow\">in<\/span> <span class=\"nb\">range<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">):<\/span>\n<span class=\"o\">...<\/span>        <span class=\"k\">try<\/span><span class=\"p\">:<\/span>\n<span class=\"o\">...<\/span>            <span class=\"n\">inp<\/span> <span class=\"o\">=<\/span> <span class=\"k\">yield<\/span> <span class=\"n\">j<\/span>\n<span class=\"o\">...<\/span>        <span class=\"k\">except<\/span> <span class=\"ne\">ValueError<\/span><span class=\"p\">:<\/span>\n<span class=\"o\">...<\/span>            <span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;Ignoring ValueError&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"o\">...<\/span>        <span class=\"k\">else<\/span><span class=\"p\">:<\/span>\n<span class=\"o\">...<\/span>            <span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;No exception&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"o\">...<\/span>        <span class=\"k\">finally<\/span><span class=\"p\">:<\/span>\n<span class=\"o\">...<\/span>            <span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;Finish loop&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"o\">...<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span> <span class=\"o\">=<\/span> <span class=\"n\">my_gen<\/span><span class=\"p\">()<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"kc\">None<\/span><span class=\"p\">)<\/span>\n<span class=\"mi\">0<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"s1\">&#39;a&#39;<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">No<\/span> <span class=\"n\">exception<\/span>\n<span class=\"n\">Finish<\/span> <span class=\"n\">loop<\/span>\n<span class=\"mi\">1<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"kc\">None<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">No<\/span> <span class=\"n\">exception<\/span>\n<span class=\"n\">Finish<\/span> <span class=\"n\">loop<\/span>\n<span class=\"mi\">2<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">throw<\/span><span class=\"p\">(<\/span><span class=\"ne\">ValueError<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">Ignoring<\/span> <span class=\"ne\">ValueError<\/span>\n<span class=\"n\">Finish<\/span> <span class=\"n\">loop<\/span>\n<span class=\"mi\">3<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">throw<\/span><span class=\"p\">(<\/span><span class=\"ne\">RuntimeError<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">Finish<\/span> <span class=\"n\">loop<\/span>\n<span class=\"n\">Traceback<\/span> <span class=\"p\">(<\/span><span class=\"n\">most<\/span> <span class=\"n\">recent<\/span> <span class=\"n\">call<\/span> <span class=\"n\">last<\/span><span class=\"p\">):<\/span>\n  <span class=\"n\">File<\/span> <span class=\"s2\">&quot;&lt;stdin&gt;&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">line<\/span> <span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"ow\">in<\/span> <span class=\"o\">&lt;<\/span><span class=\"n\">module<\/span><span class=\"o\">&gt;<\/span>\n  <span class=\"n\">File<\/span> <span class=\"s2\">&quot;&lt;stdin&gt;&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">line<\/span> <span class=\"mi\">4<\/span><span class=\"p\">,<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">my_gen<\/span>\n<span class=\"ne\">RuntimeError<\/span>\n<\/code><\/pre><\/div>\n\n<p>If the generator is exhausted than any exceptions thrown in are immediately\nre-raised.<\/p>\n<h2 id=\"close-channel\"><code>close<\/code> channel<\/h2>\n<p>Sometimes the outer caller of a generator needs to tell the co-routine to clean\nup and drop-dead.  This is done via the <code>gen.close()<\/code> method which will cause a\n<code>GeneratorExit<\/code> exepction to be raised at the point where the co-routine is\nsuspended (the <code>yield<\/code>).  If the co-routine catches this exception and tries to\nyield additional values, then <code>close()<\/code> will raise a <code>RuntimeError<\/code>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"k\">def<\/span><span class=\"w\"> <\/span><span class=\"nf\">my_gen<\/span><span class=\"p\">():<\/span>\n<span class=\"o\">...<\/span>     <span class=\"k\">for<\/span> <span class=\"n\">j<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">count<\/span><span class=\"p\">():<\/span>\n<span class=\"o\">...<\/span>         <span class=\"k\">try<\/span><span class=\"p\">:<\/span>\n<span class=\"o\">...<\/span>             <span class=\"k\">yield<\/span> <span class=\"n\">j<\/span>\n<span class=\"o\">...<\/span>         <span class=\"k\">except<\/span> <span class=\"ne\">GeneratorExit<\/span><span class=\"p\">:<\/span>\n<span class=\"o\">...<\/span>             <span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;I refuse to exit&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"o\">...<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span> <span class=\"o\">=<\/span> <span class=\"n\">my_gen<\/span><span class=\"p\">()<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"kc\">None<\/span><span class=\"p\">)<\/span>\n<span class=\"mi\">0<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"kc\">None<\/span><span class=\"p\">)<\/span>\n<span class=\"mi\">1<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"kc\">None<\/span><span class=\"p\">)<\/span>\n<span class=\"mi\">2<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">close<\/span><span class=\"p\">()<\/span>\n<span class=\"n\">I<\/span> <span class=\"n\">refuse<\/span> <span class=\"n\">to<\/span> <span class=\"n\">exit<\/span>\n<span class=\"n\">Traceback<\/span> <span class=\"p\">(<\/span><span class=\"n\">most<\/span> <span class=\"n\">recent<\/span> <span class=\"n\">call<\/span> <span class=\"n\">last<\/span><span class=\"p\">):<\/span>\n  <span class=\"n\">File<\/span> <span class=\"s2\">&quot;&lt;stdin&gt;&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">line<\/span> <span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"ow\">in<\/span> <span class=\"o\">&lt;<\/span><span class=\"n\">module<\/span><span class=\"o\">&gt;<\/span>\n<span class=\"ne\">RuntimeError<\/span><span class=\"p\">:<\/span> <span class=\"n\">generator<\/span> <span class=\"n\">ignored<\/span> <span class=\"ne\">GeneratorExit<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>The reason that <code>GeneratorExit<\/code> is not suppressible is that it is as part of\ngarbage collection and Python must be able to clean up the co-routine.<\/p>\n<p>If the co-routine catches the exception and <code>returns<\/code> there is no way for the\nouter caller to access the returned value.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"k\">def<\/span><span class=\"w\"> <\/span><span class=\"nf\">my_gen<\/span><span class=\"p\">():<\/span>\n<span class=\"o\">...<\/span>     <span class=\"k\">for<\/span> <span class=\"n\">j<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">count<\/span><span class=\"p\">():<\/span>\n<span class=\"o\">...<\/span>         <span class=\"k\">try<\/span><span class=\"p\">:<\/span>\n<span class=\"o\">...<\/span>             <span class=\"k\">yield<\/span> <span class=\"n\">j<\/span>\n<span class=\"o\">...<\/span>         <span class=\"k\">except<\/span> <span class=\"ne\">GeneratorExit<\/span><span class=\"p\">:<\/span>\n<span class=\"o\">...<\/span>             <span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;I acquiese to your request.&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"o\">...<\/span>             <span class=\"k\">return<\/span> <span class=\"s1\">&#39;Aardvark&#39;<\/span>\n<span class=\"o\">...<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span> <span class=\"o\">=<\/span> <span class=\"n\">my_gen<\/span><span class=\"p\">()<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"kc\">None<\/span><span class=\"p\">)<\/span>\n<span class=\"mi\">0<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"kc\">None<\/span><span class=\"p\">)<\/span>\n<span class=\"mi\">1<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">send<\/span><span class=\"p\">(<\/span><span class=\"kc\">None<\/span><span class=\"p\">)<\/span>\n<span class=\"mi\">2<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">gen<\/span><span class=\"o\">.<\/span><span class=\"n\">close<\/span><span class=\"p\">()<\/span>\n<span class=\"n\">I<\/span> <span class=\"n\">acquiese<\/span> <span class=\"n\">to<\/span> <span class=\"n\">your<\/span> <span class=\"n\">request<\/span><span class=\"o\">.<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>This is particularly useful if the co-routine is holding onto resources, such\nas open files or sockets, that need to be gracefully shut down.<\/p>","category":[{"@attributes":{"term":"Computer Science"}},{"@attributes":{"term":"coroutines"}},{"@attributes":{"term":"python"}}]},{"title":"How this site is maintained and published","link":{"@attributes":{"href":"https:\/\/tacaswell.github.io\/tech-details.html","rel":"alternate"}},"published":"2022-07-03T22:00:00-04:00","updated":"2022-07-24T13:00:00-04:00","author":{"name":"Thomas A Caswell"},"id":"tag:tacaswell.github.io,2022-07-03:\/tech-details.html","summary":"<p>A good and proper navel gaze.<\/p>","content":"<p><strong>Hosting<\/strong><\/p>\n<p>Both the <a href=\"https:\/\/github.com\/tacaswell\/tacaswell.github.io\">source<\/a> and built\nartifacts for this site are hosted on GitHub (via <a href=\"https:\/\/pages.github.com\">github pages<\/a>).<\/p>\n<p>It is possible to have a public gh-pages site with a private repository backing\nit, however I have opted to have both public.  This has the upsides that I can\n<a href=\"https:\/\/github.com\/tacaswell\/tacaswell.github.io\/pulls?q=is%3Apr+is%3Aclosed\">get PRs from\nothers<\/a>\nand that it is easier for other people to adapt this set up for their own use.\nA slight downside is that the history of my edits is visible, including for\ndraft posts.  I expect this to only be an issue if I write about any sensitive\ntopics where I do not want to make my full writing process public (I&rsquo;m all for\nopenness and working in public, but even I have limits).<\/p>\n<p><strong>Framework<\/strong><\/p>\n<p>This site is written within the <a href=\"http:\/\/getpelican.com\">Pelican<\/a> framework.<\/p>\n<p>I did not do exhaustive research to pick Pelican (but it does well in a google\nsearch for &ldquo;python static site generator&rdquo;), however it is in Python (hopefully\nI won&rsquo;t have to dig into the guts, but nice to know I can if I have\/want to),\ngenerates static html (needed for gh-pages hosting), and supports both markdown\nand rst out-of-the-box.<\/p>\n<p>The other framework I considered was\n<a href=\"https:\/\/www.sphinx-doc.org\/en\/master\/\">Sphinx<\/a>.  I work with Sphinx almost\nevery day for writing documentation, so it is a tool I know.  However, I wanted\nboth wanted to try a new tool and to use tool more tuned to blog\nout-of-the-box.<\/p>\n<p><strong>Theme<\/strong><\/p>\n<p>The theme is base on <a href=\"https:\/\/github.com\/jody-frankowski\/blue-penguin\">Blue\nPenguin<\/a> which is licensed\nPublic Domain.  Knowing that I was going to use GHA to build and publish the\nsite, the theme is simply <a href=\"https:\/\/github.com\/tacaswell\/tacaswell.github.io\/tree\/main\/themes\/blue-penguin\">checked\ninto<\/a>\nthe source.  I have modified a number of things, in particular the styling\naround code snippets, the base colors, and fonts (with considerable help from\nmy wife).<\/p>\n<p>If anyone else wants to use these modifications, I would be willing to split it\noff into its own repo (and use git submodules), but doing that up front seems\nlike premature optimization.<\/p>\n<p>The theme is selected via the <code>PELICANOPTS=-t $(BASEDIR)\/themes\/blue-penguin<\/code>\nline in the\n<a href=\"https:\/\/github.com\/tacaswell\/tacaswell.github.io\/blob\/3e2507fdb3812f3c74cf3076a4e037a07e1c9b7f\/Makefile#L10\">Makefile<\/a>.<\/p>\n<p><strong>Build Pipeline<\/strong><\/p>\n<p>To publish the built artifacts, I use a <a href=\"https:\/\/github.com\/tacaswell\/tacaswell.github.io\/blob\/main\/.github\/workflows\/publish.yml\">GHA\nworkflow<\/a>\nand the amazingly awesome <a href=\"https:\/\/github.com\/peaceiris\/actions-gh-pages\">gh-pages action<\/a> from\n<a href=\"https:\/\/github.com\/peaceiris\">peaciris<\/a>.<\/p>","category":[{"@attributes":{"term":"Navel Gazing"}},{"@attributes":{"term":"hosting"}}]},{"title":"No magic, only engineering","link":{"@attributes":{"href":"https:\/\/tacaswell.github.io\/no-magic-only-engineering.html","rel":"alternate"}},"published":"2022-05-25T21:00:00-04:00","updated":"2022-05-25T21:00:00-04:00","author":{"name":"Thomas A Caswell"},"id":"tag:tacaswell.github.io,2022-05-25:\/no-magic-only-engineering.html","summary":"<p>Computers are not magic, but there is some very slick engineering out there.<\/p>","content":"<blockquote>\n<p>&ldquo;Any sufficiently advanced technology is indistinguishable from magic.&rdquo;<\/p>\n<p>Arthur C Clark<\/p>\n<\/blockquote>\n<p>In the context of this well known Arthur C Clark quote, it is common to various\naspects of software called &ldquo;magic&rdquo;. Slack has a sign-in workflow that they call\n<a href=\"https:\/\/www.waveguide.io\/examples\/entry\/passwordless-login\/\">&ldquo;magic link&rdquo;<\/a>\nand I will colloquially refer to command line methods as\n<a href=\"https:\/\/tacaswell.github.io\/think-like-git.html\">&ldquo;incantations<\/a>.  However, <a href=\"https:\/\/blog.nelhage.com\/post\/computers-can-be-understood\/\">computers can be\nunderstood<\/a>.  This\nquote should be re-framed more optimistic way as:<\/p>\n<blockquote>\n<p>&ldquo;All &lsquo;magic&rsquo; is just good engineering&rdquo;<\/p>\n<\/blockquote>\n<p>This framing acknowledges the hard work that goes into making computers &ldquo;just\nwork&rdquo;.  The next time you use an computer and it is perfect, smooth experience\nthat exactly solves your problem remember there was a team of people who worked\nvery hard to make that happen.  There is work at every level, from designing\nthen interaction, to implementing the layers involved, to making sure the\nservices at every layer of the stack are running to designing and fabricating\nthe hardware.  If any layer of this (massive) stack does not work just right,\nyour experience will fail.<\/p>\n<p>I find this an empowering point of view.  Magic is mystical, arcane, something\nsecret that is closely held, something that you have to be born with, something\nsuper natural.  Once something is deemed &ldquo;magic&rdquo; it is out of the ken of mere\nmortals; it must be accepted as-is, there is no point in even trying.<\/p>\n<p>On the other hand science and engineering exist to be understood.  They are\nsystematic frameworks to understand the physical world and bend it to our will\nrespectively.  Understanding any given system (natural or engineered) may not\nbe easy and may take more time and energy than you want to spend, but it is\nalways possible in principle.  The statement is never &ldquo;I can not understand\nthis&rdquo;, it is always &ldquo;I do not understand this <em>yet<\/em>&rdquo;.<\/p>\n<p>The tools and methods of science and engineering are open to anyone who has the\ntime, resources, and inclination to use them; anyone who says differently\n(<a href=\"https:\/\/youtu.be\/KS_f6O8mWsk\">like those who deny life is pain<\/a>) is selling\nsomething.  However, while this position is well and good in theory, in reality\nthere are massive structural inequalities in who actually participates in STEM\nbroadly and open source development specifically.  It is incumbent on those of\nus who work in STEM fields to ensure equitable access and opportunity to all.\nJust like a good science challenge this is not going to be easy, but it must be\n&ldquo;We have not fixed this <em>yet<\/em>&rdquo;.<\/p>\n<p><strong>Reference<\/strong><\/p>\n<ul>\n<li><a href=\"https:\/\/lab.cccb.org\/en\/arthur-c-clarke-any-sufficiently-advanced-technology-is-indistinguishable-from-magic\/\">Art responding to the Arthur C Clark\n  quote<\/a>\n  I am (obviously) not the first person to re-imagine and re-frame this quote.<\/li>\n<li>FSF <a href=\"https:\/\/fsfe.org\/freesoftware\/#freedoms\">Four Freedoms<\/a> of open\n  software.  Proprietary systems can be reverse-engineered, but understanding a\n  system is far easier if you can read the source<\/li>\n<\/ul>","category":[{"@attributes":{"term":"Software Development"}},{"@attributes":{"term":"software"}}]},{"title":"Think Like Git","link":{"@attributes":{"href":"https:\/\/tacaswell.github.io\/think-like-git.html","rel":"alternate"}},"published":"2022-05-24T01:00:00-04:00","updated":"2022-05-24T22:35:00-04:00","author":{"name":"Thomas A Caswell"},"id":"tag:tacaswell.github.io,2022-05-24:\/think-like-git.html","summary":"<p>This article is for people who already know how to use <code>git<\/code> day-to-day, but\nwant a deeper understand of the <em>why<\/em> of <code>git<\/code> to do a better job reasoning\nabout what should or should not be possible rather than just memorizing\nincantations.<\/p>","content":"<p>While this text is going to (mostly) refer to the <code>git<\/code> CLI because it is the\nlowest common denominator (everyone who uses <code>git<\/code> has access to the CLI), there\nare many richer graphical user interfaces available (likely built into your\nIDE).  There is nothing wrong with using a GUI for working with <code>git<\/code> nor is\nthe CLI &ldquo;morally superior&rdquo; &ndash; anyone who says otherwise is engaging in\ngatekeeping nonsense.  I personally use <a href=\"https:\/\/magit.vc\/\">magit<\/a> and\n<a href=\"https:\/\/git-scm.com\/docs\/gitk\/\">gitk<\/a> in my day-to-day work.  <a href=\"https:\/\/xkcd.com\/378\/\">Real\nprogramers<\/a> use tools that make them effective, if a GUI\nmakes your life easier use it.<\/p>\n<p>For each of the CLI interfaces I&rsquo;m highlighting I am only covering the\nfunctionality relevant to the point I&rsquo;m making.  Many of these CLIs can do more\n(and sometimes wildly different) things, see the links back to the\ndocumentation for the full details.<\/p>\n<p>This article is focused on the version tracking aspect of <code>git<\/code>.  I will only\ntouch in passing on the fact that <code>git<\/code> uses <a href=\"https:\/\/git-scm.com\/book\/en\/v2\/Git-Internals-Git-Objects\">content based\naddressing<\/a> and how\nit actually encodes the state of the repository at each commit.  These details\nare interesting in their own right and critical to the implementation of <code>git<\/code>\nbeing efficient (both time and space wise), but are out of scope for this\narticle.<\/p>\n<p>Another article in a similar vein to this, but starting from a user story and\nbuilding up is <a href=\"https:\/\/tom.preston-werner.com\/2009\/05\/19\/the-git-parable.html\">the Git Parable\n<\/a>.  When I read\nthis essay years ago it made <code>git<\/code> &ldquo;click&rdquo; for me.  If you have not read it, I\nsuggest you go read it instead of this!<\/p>\n<p><strong>Table of Contents<\/strong><\/p>\n<div class=\"toc\">\n<ul>\n<li><a href=\"#gits-view-of-the-world\">git&rsquo;s view of the world<\/a><\/li>\n<li><a href=\"#what-does-it-mean-to-be-distributed-but-centralized\">What does it mean to be distributed (but centralized)?<\/a><\/li>\n<li><a href=\"#get-a-graph-to-work-with\">Get a graph to work with<\/a><\/li>\n<li><a href=\"#label-a-commit\">Label a commit<\/a><\/li>\n<li><a href=\"#compare-source-between-nodes\">Compare source between nodes<\/a><\/li>\n<li><a href=\"#look-at-the-whole-tree\">Look at the whole tree<\/a><\/li>\n<li><a href=\"#look-at-a-node\">Look at a node<\/a><\/li>\n<li><a href=\"#adding-nodes\">Adding nodes<\/a><\/li>\n<li><a href=\"#discard-changes\">discard changes<\/a><\/li>\n<li><a href=\"#change-or-move-nodes\">change or move nodes<\/a><\/li>\n<li><a href=\"#sharing-with-your-friends\">Sharing with your friends<\/a><\/li>\n<li><a href=\"#checking-out-more-than-one-commit\">checking out more than one commit<\/a><\/li>\n<li><a href=\"#git-config\">git config<\/a><\/li>\n<li><a href=\"#other-things-you-might-want-to-do\">Other things you might want to do<\/a><\/li>\n<li><a href=\"#other-resources\">Other resources<\/a><\/li>\n<li><a href=\"#acknowledgments\">Acknowledgments<\/a><\/li>\n<\/ul>\n<\/div>\n<h2 id=\"gits-view-of-the-world\">git&rsquo;s view of the world<\/h2>\n<p>At the core, <code>git<\/code> keeps track of many (many) copies of your code, creating a\nsnapshot whenever you commit.  Along with the code, <code>git<\/code> attaches to each a\nblock of text, information about who and when the code was written and\ncommitted, and what commits are the &ldquo;parents&rdquo; to from a <strong>commit<\/strong>.  The hash\nof all of this serves both as a globally unique name for the commit and to\nvalidate the commit.<\/p>\n<p>Because each commit knows its parent(s), the commits form a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Directed_acyclic_graph\">directed acyclic\ngraph<\/a> (DAG).  The code\nsnap-shots and metadata are the nodes, the parents relationships define the\nedges, and because you can only go backwards in history (commits do not know\nwho their children are) it is directed.  DAG&rsquo;s are a relatively common data\nstructure in programming (and if you need to work with them in Python checkout\n<a href=\"http:\/\/networkx.org\/documentation\/stable\/\">networkx<\/a>).  By identifying a DAG\nas the core data structure of <code>git<\/code>&rsquo;s view of history we can start to develop\nintuition of what operations will be easy on <code>git<\/code> history (if they would be\neasy to express via operations on a DAG).  Using this intuition, we can\n(hopefully) start to guess how <code>git<\/code> would probably implement the functionality\nwe need to actually get our work done!<\/p>\n<p>Because the hash includes information about the parents the tree of commits\nforms a variation on a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Merkle_tree\">Merkle\nTree<\/a>.  Using these hashes you can\nvalidate that a <code>git<\/code> repository is self consistent and that the source you\nhave checked out is indeed the source that was checked in.  If you and a\ncollaborator both have a clone of a shared project then they can send you just\nthe hash of a commit and you can be sure that you have both an identical\nworking tree and identical history.<\/p>\n<p>Given such a graph, what operations would we want to do to it?  For example we\nwant to<\/p>\n<ol>\n<li>get a repository to work with (<code>git clone<\/code>, <code>git init<\/code>)<\/li>\n<li>give commits human readable names (<code>git tag<\/code>, <code>git branch<\/code>)<\/li>\n<li>compare source between commits (<code>git diff<\/code>)<\/li>\n<li>look at the whole graph of commits (<code>gitk<\/code>, <code>git log<\/code>)<\/li>\n<li>look at a commit (both the code content and meta-data) (<code>gitk<\/code>, <code>git switch<\/code>, <code>git checkout<\/code>)<\/li>\n<li>add commits (<code>git stage<\/code>, <code>git add<\/code>)<\/li>\n<li>discard changes (both local changes and whole commits) (<code>git reset<\/code>, <code>git restore<\/code>, <code>git clean<\/code>, <code>git checkout<\/code>)<\/li>\n<li>change\/move commits around the graph (<code>git rebase<\/code>, <code>git cherry-pick<\/code>)<\/li>\n<li>share your code (and history) with your friends (<code>git push<\/code>, <code>git fetch<\/code>, <code>git remote<\/code>, <code>git merge<\/code>)<\/li>\n<li>have more than one commit checked out at a time (<code>git worktree<\/code>)<\/li>\n<\/ol>\n<h2 id=\"what-does-it-mean-to-be-distributed-but-centralized\">What does it mean to be distributed (but centralized)?<\/h2>\n<p>From a technical stand point no clone of a <code>git<\/code> repository is more special\nthan any other.  Each contains a self consistent section of the history of the\nrepository and they can all share that information with each other.  From a\ncertain point of view, there is only one global history which consists of every\ncommit any developer on any computer has ever created and any given computer\nonly ever has a sub-graph of the full history.<\/p>\n<p>While technically pure, fully distributed collaboration is deeply impractical.\nAlmost every project has socially picked a central repository to be considered\nthe &ldquo;canonical&rdquo; repository.  For example for Matplotlib\n<a href=\"https:\/\/github.com\/matplotlib\/matplotlib\">matplotlib\/matplotlib<\/a> is <em>the<\/em> ground\ntruth repository.  At the end of the day what <em>is<\/em> Matplotlib the library is\nthat git history, full stop.  Because of the special social role that\nrepository holds only people with commit rights are able to push to that\nrepository and we have a agreed on social process for deciding who gets that\naccess and what code gets merged.  When people talk about a project having a\n&ldquo;hard fork&rdquo; or a &ldquo;hostile fork&rdquo; they are referring to a community that has\nsplit about which repository is &ldquo;the one&rdquo; and who has the ability to push to\nit.<\/p>\n<p>Similarly, while every commit has a (gloablly) unique name &ndash; its hash &ndash; they\nare effectively unusable.  The branch and tag names that we use are for the\nhumans and any meaning we attach to the names is purely social.  Within the\ncanonical repository there is a particular branch which is identified as <em>the<\/em>\nbranch for new development along and optionally a handful of other &ldquo;official&rdquo;\nbranches for maintaining bug-fix series. The exact details of the names, the\nlife cycles and the development workflow will vary from team-to-team.  For\nexample on Matplotlib we have a <code>main<\/code> branch for new development, the <code>vX.Y.x<\/code>\nbranches which are the maintenance branches for each <code>vX.Y.0<\/code> minor release,\nand <code>vX.Y-doc<\/code> for the version specific documentation.  To <code>git<\/code> these names\nare meaningless, but socially they are critical.<\/p>\n<p>In the standard fork-based development workflow that many open source software\nprojects use the commits move from less visible but loosely controlled parts of\nthe global graphs to more public and controlled parts.  For example anyone can\ncreate commits on their local clone at will!  However no one else can (easily)\nsee them and those commits are inaccessible to almost everyone else who has\npart of the total graph.  A developer can then choose to publish their commits\nto a public location (for example I push all of my work on Matplotlib to\n<a href=\"https:\/\/github.cm\/tacaswell\/matplotlib\">tacaswell\/matplotlib<\/a> first).  Once\nthe commits are public anyone can see them but only a handful of people are\nlikely to actually access them.  To get the code into the canonical repository,\nand hence used by everyone, the user can request that the committers to the\ncanonical repository &ldquo;pull&rdquo; or &ldquo;merge&rdquo; their branch into the default branch.\nIf this &ldquo;pull request&rdquo; is accepted and merged to the default branch then that\ncode (and commit history) is forever part of the project&rsquo;s history.<\/p>\n<h2 id=\"get-a-graph-to-work-with\">Get a graph to work with<\/h2>\n<p>The most common way to get a copy of a project history is not to start <em>ab initio<\/em>,\nbut to get a copy of a preexisting history.  Any given project only starts\nonce, but over time will receive many more commits (this repository already has\n20+ commits, Matplotlib has over 43k, the kernel has <a href=\"https:\/\/www.linuxfoundation.org\/blog\/the-one-millionth-commit-the-search-for-the-lucky-linux-kernel-contributor\/\">over 1\nmillion<\/a>).<\/p>\n<p>To get a local copy of a repository so you can start working on it you use the\n<code>git clone<\/code> <a href=\"https:\/\/git-scm.com\/docs\/git-clone\">sub-command<\/a>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>clone<span class=\"w\"> <\/span>url_to_remote<span class=\"w\">    <\/span><span class=\"c1\"># will create a new directory in the CWD<\/span>\n<\/code><\/pre><\/div>\n\n<p>By default <code>git<\/code> will fetch everything from the remote repository (there are\nways <a href=\"https:\/\/github.blog\/2020-12-21-get-up-to-speed-with-partial-clone-and-shallow-clone\/\">to reduces this for big\nrepositories<\/a>).\nIf you clone from the canonical repository then you have the complete\nup-to-date official history of the project on your computer!<\/p>\n<p>If you need to create a new repository use the <code>git init<\/code>\n<a href=\"https:\/\/git-scm.com\/docs\/git-init\">sub-command<\/a>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>init\n<\/code><\/pre><\/div>\n\n<p>However, I have probably only ever used <code>git init<\/code> a few dozen times in my\ncareer, where as I use <code>git clone<\/code> a few dozen times a week.<\/p>\n<h2 id=\"label-a-commit\">Label a commit<\/h2>\n<p>From the hash we have a globally unique identifier for each commit, however\nthese hashes look something like: <code>6f8bc7c6f192f664a7ab2e4ff200d050bb2edc8f<\/code>.\nWhile unique and well-suited for a computer, it is neither memorable nor does\nit roll off the tongue.  This is partly ameliorated because anyplace that the\n<code>git<\/code> interface takes a SHA you can instead pass a prefix, e.g.  <code>6f8bc7<\/code> for\nthe SHA above.  However the number of characters needed ensure the that the\nprefix is actually unique <a href=\"https:\/\/blog.cuviper.com\/2013\/11\/10\/how-short-can-git-abbreviate\/\">depends on the size of the\nrepository<\/a>.<\/p>\n<p>To give a human-friendly name to a commit git offers two flavors of labels:\n<strong>branches<\/strong> and <strong>tags<\/strong>.  The conceptual difference is that a <strong>branch<\/strong> is\nexpected to move between commits over time and <strong>tags<\/strong> are fixed to a\nparticular commit for all time.<\/p>\n<p><strong>Branches<\/strong> point to a fixed <em>concept<\/em>.  As discussed above, most repositories\nhave a socially designated &ldquo;canonical branch&rdquo; that is the point of truth for\nthe development effort.  The exact name does not matter, but common names\ninclude &ldquo;main&rdquo;, &ldquo;trunk&rdquo;, or &ldquo;devel&rdquo;.  It is also conventional to do new\ndevelopment on a &ldquo;development&rdquo; branch, named anything but the canonical branch\nname.  This enables you to keep multiple independent work directions in flight\nat a time and easily discard any work turns out to be less of a good idea than\nyou thought.<\/p>\n<p>To list, create, and delete branches use the <code>git branch<\/code>\n<a href=\"https:\/\/git-scm.com\/docs\/git-branch\">sub-command<\/a>.  The most important\nincantations are:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>branch<span class=\"w\">            <\/span><span class=\"c1\"># list local branches<\/span>\ngit<span class=\"w\"> <\/span>branch<span class=\"w\"> <\/span>-c<span class=\"w\"> <\/span>&lt;name&gt;<span class=\"w\">  <\/span><span class=\"c1\"># create a branch<\/span>\ngit<span class=\"w\"> <\/span>branch<span class=\"w\"> <\/span>-d<span class=\"w\"> <\/span>&lt;name&gt;<span class=\"w\">  <\/span><span class=\"c1\"># delete a branch, if safe<\/span>\ngit<span class=\"w\"> <\/span>branch<span class=\"w\"> <\/span>-D<span class=\"w\"> <\/span>&lt;name&gt;<span class=\"w\">  <\/span><span class=\"c1\"># delete a branch over git&#39;s concerns<\/span>\n<\/code><\/pre><\/div>\n\n<p>In <code>git<\/code> branches are cheap to make, when in doubt, make a new branch!<\/p>\n<p>In contrast <strong>tags<\/strong> label a specific commit and never move.  This is used most\noften for identifying released versions of software (e.g. v1.5.2).  To work with <strong>tags<\/strong>\nuse the <code>git tag<\/code> <a href=\"https:\/\/git-scm.com\/docs\/git-tag\">sub-command<\/a>.  The most important incantations\nare:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>tag<span class=\"w\">           <\/span><span class=\"c1\"># list tags<\/span>\ngit<span class=\"w\"> <\/span>tag<span class=\"w\"> <\/span>-a<span class=\"w\"> <\/span>&lt;name&gt;<span class=\"w\"> <\/span><span class=\"c1\"># create a new tag<\/span>\n<\/code><\/pre><\/div>\n\n<p>You should always create &ldquo;annotated&rdquo; tags.  If the commit is important enough\nto get a permanent name, it is important enough get an explanation of why you\ngave it a name.<\/p>\n<p>In <code>git<\/code> jargon these are &ldquo;refs&rdquo;.  See <a href=\"https:\/\/git-scm.com\/book\/en\/v2\/Git-Internals-Git-References\">the\ndocs<\/a> if you want\neven more details about how <code>git<\/code> encodes these.<\/p>\n<h2 id=\"compare-source-between-nodes\">Compare source between nodes<\/h2>\n<p>There is a &ldquo;dual space&rdquo; relationship between the code state at each commit and\nthe differences between the commits.  If you have one you can always compute\nthe other. On first glance the natural way to track the changes of source over\ntime is to track the differences (this is in fact how many earlier version\ncontrol systems worked!).  However git (and mercurial) instead track the full\nstate of the of the source at each commit which solves a number of performance\nproblems and enables some additional operations.<\/p>\n<p>Because the diffs between subsequent commits are derived, it is just as easy to\ncompute the diff between any two commits!  Using the <code>git diff<\/code>\n<a href=\"https:\/\/git-scm.com\/docs\/git-diff\">sub-command<\/a>.  To get the difference between two\ncommits :<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>diff<span class=\"w\"> <\/span>&lt;before&gt;<span class=\"w\"> <\/span>&lt;after&gt;\n<\/code><\/pre><\/div>\n\n<p>which will give you a patch that if applied to the <code>&lt;before&gt;<\/code> commit will land\nyou at the <code>&lt;after&gt;<\/code> commit.  If you want to get a patch that will undo a\nchange swap the order of the commits.<\/p>\n<p>Calling <code>git diff<\/code> without any arguments is very common command that will show\nany uncommitted changes in your working tree.<\/p>\n<h2 id=\"look-at-the-whole-tree\">Look at the whole tree<\/h2>\n<p>It is useful to look at the whole graph.  There is the <code>git log<\/code>\n<a href=\"https:\/\/git-scm.com\/docs\/git-log\">sub-command<\/a> which will show you text\nversions of history, however this is an application where a GUI interface\nreally shines.  There is so much information available:<\/p>\n<ul>\n<li>the commit message<\/li>\n<li>the author and committer<\/li>\n<li>dates<\/li>\n<li>the computed diffs<\/li>\n<li>the connectivity between the commits<\/li>\n<\/ul>\n<p>that it is difficult to see it all and navigate it in a pure text interface.<\/p>\n<p>My preferred tool for exploring the full history is\n<a href=\"https:\/\/git-scm.com\/docs\/gitk\/\">gitk<\/a> which is typically installed with git.\nIt is a bit ugly, but it works!  In addition to visualizing the tree it also\nhas a user interface for searching both the commit messages and the code\nchanges and for limiting the history to only particular files.<\/p>\n<h2 id=\"look-at-a-node\">Look at a node<\/h2>\n<p>When working with a git repository on your computer you almost always have one\nof the commits materialized into a working tree (or more than one with the\n<code>git worktree<\/code> <a href=\"https:\/\/git-scm.com\/docs\/git-worktree\">sub-command<\/a>).  The working\ntree is, as the name suggests, where you actually do your work!  We will come\nback to this in the next section.<\/p>\n<p>To checkout a particular <strong>commit<\/strong> (or <strong>tag<\/strong> or <strong>branch<\/strong>) you can use the\n<code>git checkout<\/code> <a href=\"https:\/\/git-scm.com\/docs\/git-checkout\">sub-command<\/a> as<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>checkout<span class=\"w\"> <\/span>&lt;commit<span class=\"w\"> <\/span>hash&gt;<span class=\"w\">  <\/span><span class=\"c1\"># checks out a particular commit<\/span>\ngit<span class=\"w\"> <\/span>checkout<span class=\"w\"> <\/span>&lt;tag<span class=\"w\"> <\/span>name&gt;<span class=\"w\">     <\/span><span class=\"c1\"># checks out a particular tag<\/span>\ngit<span class=\"w\"> <\/span>checkout<span class=\"w\"> <\/span>&lt;branch<span class=\"w\"> <\/span>name&gt;<span class=\"w\">  <\/span><span class=\"c1\"># checks out a particular branch<\/span>\n<\/code><\/pre><\/div>\n\n<p>In addition, there is also a new <code>git switch<\/code>\n<a href=\"https:\/\/git-scm.com\/docs\/git-switch\">sub-command<\/a> that is specifically for\nswitching branches.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>switch<span class=\"w\"> <\/span>&lt;branch&gt;\n<\/code><\/pre><\/div>\n\n<p>which is more scoped (<code>git checkout<\/code> has a number of other features) and\nclearly named.<\/p>\n<p>If you want to see the history of what commits you have had checked out (as\nopposed to the history the repository) you can use the <code>git reflog<\/code>\n<a href=\"https:\/\/git-scm.com\/docs\/git-reflog\">sub-command<\/a>.  While not something to use\nday-to-day, it can save your bacon in cases where you have accidentally lost\nreferences to a commit.<\/p>\n<h2 id=\"adding-nodes\">Adding nodes<\/h2>\n<p>The most important, and likely most common, operation we do on the graph is to\nadd new commits!<\/p>\n<p>As mention above when you checkout a branch on your computer you have a working\ntree that starts at the state of the commit you have checked out.  There is\nspecial name that can be used as a commit <code>HEAD<\/code> which means &ldquo;the commit that\nis currently checked out in your work tree&rdquo;.  There is also the short hand\n<code>HEAD^<\/code> which means &ldquo;the commit before the one checked out&rdquo;, <code>HEAD^^<\/code> which\nmeans &ldquo;the commit two before the one checked out&rdquo;, and so on for repeated <code>^<\/code>.<\/p>\n<p>As you make changes there are two common commands <code>git status<\/code>\n<a href=\"https:\/\/git-scm.com\/docs\/git-status\">sub-command<\/a> and <code>git diff<\/code>\n<a href=\"https:\/\/git-scm.com\/docs\/git-diff\">sub-command<\/a>.  <code>git status<\/code> will give you a\nsummary of what changes you have in the local tree, relative to <code>HEAD<\/code> and what\nchanges are staged. <code>git diff<\/code>, when called with no arguments will show the detailed\ndiff between the current working tree and <code>HEAD<\/code>.<\/p>\n<p>As you work on your code, <code>git<\/code> does not require you to commit all of your\nchanges at once, but to enable this committing is two a stage process.  The\nfirst step is to use the <code>git add<\/code>\n<a href=\"https:\/\/git-scm.com\/docs\/git-add\">sub-command<\/a> to stage changes<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>add<span class=\"w\"> <\/span>path\/to\/file<span class=\"w\">  <\/span><span class=\"c1\"># to stage all the changes in a file<\/span>\ngit<span class=\"w\"> <\/span>add<span class=\"w\"> <\/span>-p<span class=\"w\">            <\/span><span class=\"c1\"># to commit by hunk<\/span>\n<\/code><\/pre><\/div>\n\n<p>Once you have staged all of the changes you want, you create a new commit via the\n<code>git commit<\/code> <a href=\"https:\/\/git-scm.com\/docs\/git-commit\">sub-command<\/a><\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>commit<span class=\"w\"> <\/span>-m<span class=\"w\"> <\/span><span class=\"s2\">&quot;Short Message&quot;<\/span><span class=\"w\">   <\/span><span class=\"c1\"># commit with a short commit message<\/span>\ngit<span class=\"w\"> <\/span>commit<span class=\"w\">                      <\/span><span class=\"c1\"># open an editor to write a commit message<\/span>\n<\/code><\/pre><\/div>\n\n<p>Writing a commit message is one of the most important parts of using git.\nWhile it is frequently possible to, only from the source, reconstruct the what\nof a code change it can be impossible to reconstruct the <em>why<\/em> of the change.\nThe commit message is a place that you can leave notes to your collaborators\nexplaining the motivations of the change.  Remember that your most frequent\ncollaborator is your future \/ past self!  For a comprehensive guide to writing\ngood commit messages see <a href=\"https:\/\/cbea.ms\/git-commit\/\">this article<\/a>.<\/p>\n<p>As <code>git<\/code> encourages the creation of <strong>branches<\/strong> for new development, when the\nwork is done (via the cycle above) we will need to merge this work back into\nthe canonical branch which is done via the <code>git merge<\/code>\n<a href=\"https:\/\/git-scm.com\/docs\/git-merge\">sub-command<\/a>.  By default, this will\ncreate a new commit on your current branch who has two parents (the tips of\neach branch involved).<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>merge<span class=\"w\"> <\/span>&lt;other<span class=\"w\"> <\/span>branch&gt;<span class=\"w\">   <\/span><span class=\"c1\"># merge other branch into the current branch<\/span>\n<\/code><\/pre><\/div>\n\n<p>If you are using a code hosting platform (GitHub, GitLab, BitBucket, &hellip;) this\ncommand will typically be done through a the web UI&rsquo;s &ldquo;merge&rdquo; button.<\/p>\n<h2 id=\"discard-changes\">discard changes<\/h2>\n<p>Not all changes are a good idea, sometimes you need to go back.<\/p>\n<p>If you have not yet committed your changes then they can be discarded using the\n<code>git checkout<\/code> <a href=\"https:\/\/git-scm.com\/docs\/git-checkout\">sub-command<\/a> (yes the\nsame one we used to change branches)<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>checkout<span class=\"w\"> <\/span>path\/to\/file<span class=\"w\">  <\/span><span class=\"c1\"># discard local changes<\/span>\n<\/code><\/pre><\/div>\n\n<p>There is also the new <code>git restore<\/code> <a href=\"https:\/\/git-scm.com\/docs\/git-restore\">sub-command<\/a>\nwhich is more tightly scoped to discarding local file changes<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>restore<span class=\"w\"> <\/span>path\/to\/file\n<\/code><\/pre><\/div>\n\n<p>If you have files in your working directory that <code>git<\/code> is not currently tracking you\ncan use the <code>git clean<\/code> <a href=\"https:\/\/git-scm.com\/docs\/git-clean\">sub-command<\/a>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>clean<span class=\"w\"> <\/span>-xfd<span class=\"w\">    <\/span><span class=\"c1\"># purge any untracked files (including ignored files)<\/span>\n<\/code><\/pre><\/div>\n\n<p>If you need to discard <strong>commits<\/strong> you can use the <code>git reset<\/code>\n<a href=\"https:\/\/git-scm.com\/docs\/git-reset\">sub-command<\/a>.  By default <code>git reset<\/code> will\nchange the currently checked out commit but not change your working tree (so you keep\nall of the code changes).<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>reset<span class=\"w\"> <\/span>HEAD^<span class=\"w\">      <\/span><span class=\"c1\"># move the branch back one, keep working tree the same<\/span>\ngit<span class=\"w\"> <\/span>reset<span class=\"w\"> <\/span>HEAD^^<span class=\"w\">     <\/span><span class=\"c1\"># move the branch back two, keep working tree the same<\/span>\ngit<span class=\"w\"> <\/span>reset<span class=\"w\"> <\/span>&lt;a<span class=\"w\"> <\/span>SHA1&gt;<span class=\"w\">   <\/span><span class=\"c1\"># move the branch a commit, keep working tree the same<\/span>\n<\/code><\/pre><\/div>\n\n<p>This can be very useful if you like the changes you made, but not the commits\nor commit messages.<\/p>\n<p>Alternatively if you want to discard the commits and the changes you can use\nthe <code>--hard<\/code> flag:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>reset<span class=\"w\"> <\/span>--hard<span class=\"w\"> <\/span>HEAD^<span class=\"w\">     <\/span><span class=\"c1\"># move the branch back one, discard all changes<\/span>\ngit<span class=\"w\"> <\/span>reset<span class=\"w\"> <\/span>--hard<span class=\"w\"> <\/span>HEAD^^<span class=\"w\">    <\/span><span class=\"c1\"># move the branch back two, discard all changes<\/span>\ngit<span class=\"w\"> <\/span>reset<span class=\"w\"> <\/span>--hard<span class=\"w\"> <\/span>&lt;a<span class=\"w\"> <\/span>SHA1&gt;<span class=\"w\">  <\/span><span class=\"c1\"># move the branch a commit, discard all changes<\/span>\n<\/code><\/pre><\/div>\n\n<p>Be aware that these can be a destructive commands!  If you move a branch back\nthere maybe commits that are inaccessible (remember commits only know their\nparents).  This is where the <code>git reflog<\/code>\n<a href=\"https:\/\/git-scm.com\/docs\/git-reflog\">sub-command<\/a> can help recover the lost\ncommits.<\/p>\n<p><code>git<\/code> commands may create objects behind the scenes that ultimately become\ninaccessible.  <code>git<\/code> will on its own clean up, but you can manually trigger\nthis clean up via <code>git gc<\/code> <a href=\"https:\/\/git-scm.com\/docs\/git-gc\">sub-command<\/a>.<\/p>\n<p>If you have accidentally committed something sensitive, but not yet pushed, you\ncan use these tools to purge it.  If you have push the commit you will need\n<a href=\"https:\/\/docs.github.com\/en\/authentication\/keeping-your-account-and-data-secure\/removing-sensitive-data-from-a-repository\">some higher test\ntools<\/a>.<\/p>\n<h2 id=\"change-or-move-nodes\">change or move nodes<\/h2>\n<p>Due to the way the hashes work in <code>git<\/code> you can not truly <em>change<\/em> a commit,\nbut you can modify and recommit it or make copies elsewhere in the graph.\nRemember that if you have already shared the commits you are replacing you will\nhave to force-push them again (see below).  Be very careful about doing this to\nany branch that many other people are using.<\/p>\n<p>If you have just created a commit and realized you need to add one more change\nyou can use the <code>--amend<\/code> flag to <code>git commit<\/code>\n<a href=\"https:\/\/git-scm.com\/docs\/git-commit\">sub-command<\/a>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\"># hack<\/span>\ngit<span class=\"w\"> <\/span>add<span class=\"w\"> <\/span>path\/to\/file<span class=\"w\">     <\/span><span class=\"c1\"># stage the changes like normal<\/span>\ngit<span class=\"w\"> <\/span>commit<span class=\"w\"> <\/span>--amend<span class=\"w\">       <\/span><span class=\"c1\"># add the changes to the HEAD commit<\/span>\n<\/code><\/pre><\/div>\n\n<p>This does not actually <em>change<\/em> the old commit.  A commit is uniquely\nidentified by its hash and the hash includes the state of the code, thus\n&ldquo;amending&rdquo; a commit creates a <em>new<\/em> commit and then resets the current branch\nto point to the new commit and orphans the old commit.<\/p>\n<p>If you want to move a range of commits from one place to another you can use\nthe <code>git rebase<\/code> <a href=\"https:\/\/git-scm.com\/docs\/git-rebase\">sub-command<\/a>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>rebase<span class=\"w\"> <\/span>target_branch<span class=\"w\">     <\/span><span class=\"c1\"># rebase the current branch onto target_branch<\/span>\n<\/code><\/pre><\/div>\n\n<p>which will attempt to &ldquo;replay&rdquo; the changes in each of the commits on your\ncurrent branch on top of <code>target_branch<\/code>.  If there are conflicts that <code>git<\/code>\ncan not automatically resolve it will pause for you to manually resolve the\nconflicts and stage the changes to continue or abort the whole rebase<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>rebase<span class=\"w\"> <\/span>--continue<span class=\"w\">   <\/span><span class=\"c1\">#  continue with your manual resolution<\/span>\ngit<span class=\"w\"> <\/span>rebase<span class=\"w\"> <\/span>--abort<span class=\"w\">      <\/span><span class=\"c1\">#  abort and go back to where you started<\/span>\n<\/code><\/pre><\/div>\n\n<p>If you want to re-order, drop or combine commits you can use:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>rebase<span class=\"w\"> <\/span>-i<span class=\"w\">                <\/span><span class=\"c1\"># interactively rebase, squash and re-order<\/span>\n<\/code><\/pre><\/div>\n\n<p>which will open an editor with instructions.  This can be particularly useful\nif you want commit early and often as you work, but when you are done re-order\nand re-arrange the changes into a smaller number of better organized commits to\ntell a better story.<\/p>\n<p>Common reasons to be asked to rebase (and squash) a branch is if your\ndevelopment branch has grown merge conflicts and the project prefers rebasing\nover merging the default branch back into the development branches or if your\ncommit history has too many &ldquo;noise&rdquo; commits (small typo fixes, reversions of\nwork, committing and then deleting files).<\/p>\n<p>To move a commit from one branch to another use the <code>git cherry-pick<\/code>\n<a href=\"https:\/\/git-scm.com\/docs\/git-cherry-pick\">sub-command<\/a> which is conceptually\nsimilar to <code>git rebase<\/code><\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>cherry-pick<span class=\"w\"> <\/span>&lt;commit&gt;<span class=\"w\">      <\/span><span class=\"c1\"># pick the commit on to the current branch<\/span>\ngit<span class=\"w\"> <\/span>cherry-pick<span class=\"w\"> <\/span>-m<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>&lt;commit&gt;<span class=\"w\"> <\/span><span class=\"c1\"># pick a merge commit onto the current branch<\/span>\ngit<span class=\"w\"> <\/span>cherry-pick<span class=\"w\"> <\/span>--continue<span class=\"w\">    <\/span><span class=\"c1\"># continue if you have to manually resolve conflicts<\/span>\ngit<span class=\"w\"> <\/span>cherry-pick<span class=\"w\"> <\/span>--skip<span class=\"w\">        <\/span><span class=\"c1\"># drop a redundant commit<\/span>\ngit<span class=\"w\"> <\/span>cherry-pick<span class=\"w\"> <\/span>--abort<span class=\"w\">       <\/span><span class=\"c1\"># give up and go back to where you started<\/span>\n<\/code><\/pre><\/div>\n\n<p>In all of these cases, <a href=\"https:\/\/git-scm.com\/docs\/git-reflog\">sub-command<\/a> can\nbe useful if things do not go as you expect!<\/p>\n<h2 id=\"sharing-with-your-friends\">Sharing with your friends<\/h2>\n<p>So far we have not talked much about any of the collaborative or distributed\nnature of git.  Except for <code>git clone<\/code>, every command so far can be done only\nwith information than <code>git<\/code> has on your computer and can be done without a\nnetwork connection.  This lets you work in your own private enclave, either\ntemporarily, because you are working on a laptop on commuter rail or are not\nyet ready to share your work, or permanently if you just prefer to work alone.<\/p>\n<p>While version control is useful if you are working alone (your most frequent\ncollaborator is your future \/ past self and version control can <a href=\"https:\/\/tacaswell.github.io\/how-i-learned-to-love-vcs.html\">save you from\ntypos<\/a>), it really shines when you are working\nwith other people.  To share code with others we need to a notion of a shared\nhistory.  Given that under the hood git is a graph of nodes uniquely named by\ntheir content &ldquo;all&rdquo; we have to do is be able to share information about the\ncommits, branches, and tags between the different computers!<\/p>\n<p>By default after an initial <code>git clone<\/code> there is one &ldquo;remote&rdquo; pointing to where\never you cloned from by default named <code>origin<\/code>.  To modify an existing remote\nor add a new remote use the <code>git remote<\/code>\n<a href=\"https:\/\/git-scm.com\/docs\/git-remote\">sub-command<\/a>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>remote<span class=\"w\"> <\/span>add<span class=\"w\"> <\/span>&lt;name&gt;<span class=\"w\"> <\/span>&lt;url&gt;<span class=\"w\">     <\/span><span class=\"c1\"># add a new remote<\/span>\ngit<span class=\"w\"> <\/span>remote<span class=\"w\"> <\/span>rm<span class=\"w\"> <\/span>&lt;name&gt;<span class=\"w\">            <\/span><span class=\"c1\"># delete a remote<\/span>\ngit<span class=\"w\"> <\/span>remote<span class=\"w\"> <\/span>rename<span class=\"w\"> <\/span>&lt;old&gt;<span class=\"w\"> <\/span>&lt;new&gt;<span class=\"w\">   <\/span><span class=\"c1\"># rename a remote from old -&gt; new<\/span>\n<\/code><\/pre><\/div>\n\n<p>Once you have one or more remotes updated the first thing we want to is be able\nto get new commits from the remotes via <code>git fetch<\/code>\n<a href=\"https:\/\/git-scm.com\/docs\/git-fetch\">sub-command<\/a> or <code>git remote<\/code>\n<a href=\"https:\/\/git-scm.com\/docs\/git-remote\">sub-command<\/a>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>fetch<span class=\"w\"> <\/span>&lt;name&gt;<span class=\"w\">      <\/span><span class=\"c1\"># fetch just one remote<\/span>\ngit<span class=\"w\"> <\/span>fetch<span class=\"w\"> <\/span>--all<span class=\"w\">       <\/span><span class=\"c1\"># fetch all of the<\/span>\ngit<span class=\"w\"> <\/span>remote<span class=\"w\"> <\/span>update<span class=\"w\">     <\/span><span class=\"c1\"># update all the remotes<\/span>\n<\/code><\/pre><\/div>\n\n<p>The <code>git pull<\/code> <a href=\"https:\/\/git-scm.com\/docs\/git-pull\">sub-command<\/a> combines a\nfetch and a merge into one command.  While this seems convenient, it will\nfrequently generate unexpected merge commits that take longer to clean up than\nbeing explicit about fetching and merging separately.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>merge<span class=\"w\"> <\/span>--ff-only<span class=\"w\"> <\/span>remote\/branch<span class=\"w\">   <\/span><span class=\"c1\"># merge remote branch into the local branch<\/span>\n<\/code><\/pre><\/div>\n\n<p>The <code>--ff-only<\/code> flag fails unless the history can be &ldquo;fast forwarded&rdquo; meaning\nthat only the remote branch has new commits.<\/p>\n<p>To share your work with others you need to put the commits someplace other\npeople can see it.  The exact details of this depend on the workflow of the\nproject and team, but if using a hosting platform this is done via the <code>git\npush<\/code> <a href=\"https:\/\/git-scm.com\/docs\/git-push\">sub-command<\/a>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>push<span class=\"w\"> <\/span>&lt;remote&gt;<span class=\"w\"> <\/span>&lt;branch_name&gt;<span class=\"w\">       <\/span><span class=\"c1\"># push the branch_name to remote<\/span>\n<\/code><\/pre><\/div>\n\n<p>Given that in a typical workflow you are likely to be pushing to the same\nbranch on the same remote many times <code>git<\/code> has streamlined ways of keeping track\nof the association between your local branch and a <a href=\"https:\/\/git-scm.com\/book\/en\/v2\/Git-Branching-Remote-Branches\">remote\nbranch<\/a> on a\n(presumably) more public location.  By telling git about this association we\nsave both typing and the chance of mistakes due to typos.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>branch<span class=\"w\"> <\/span>--set-upstream-to<span class=\"w\"> <\/span>&lt;remote&gt;<span class=\"w\"> <\/span><span class=\"c1\"># set an &quot;upstream&quot;<\/span>\ngit<span class=\"w\"> <\/span>push<span class=\"w\">                              <\/span><span class=\"c1\"># &quot;do the right thing&quot; with upstream set<\/span>\n<\/code><\/pre><\/div>\n\n<p>If you try to push commits to a remote branch that has commits that are not on\nyour local branch git will reject the push.  The course of action depends on\nwhy you are missing commits.  If there are new commits on the remote branch\nthat you have not fetched before, then you should either merge the remote\nbranch into your local branch before pushing or rebase your local branch on the\nremote branch and push again.<\/p>\n<p>Because git can not tell the difference new commits on the remote and old\ncommits on the remote because you have re-written history locally, either via\n<code>git commit --ammend<\/code> or <code>git rebase<\/code>, then you have to do something a bit ....\ndangerous.  <code>git<\/code> detecting that if the remote branch were to be updated to\nwhere the local branch it would make some commits inaccessible and protecting\nyou from yourself.  However, if you are sure we can tell <code>git<\/code> to trust our\njudgment and do it anyway:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>push<span class=\"w\"> <\/span>--force-with-lease\n<\/code><\/pre><\/div>\n\n<p>Be very careful about doing this to branches that other people are relying on\nand have checked out.  Other people will have the same problem you just had,\nbut in reverse.  <code>git<\/code> can not tell that the re-written commits are &ldquo;right&rdquo; and\nthe history on the other users computer are &ldquo;wrong&rdquo;.  They will be presented\nwith the same options you just had and may re-force-push your changes out of\nexistences.  We recently had to <a href=\"https:\/\/discourse.matplotlib.org\/t\/default-branch-renamed-with-minor-edit-to-history\/22367\">re-write the history on the default Matplotlib\nbranch<\/a>\nand it required a fair amount of planning and work to manage.<\/p>\n<h2 id=\"checking-out-more-than-one-commit\">checking out more than one commit<\/h2>\n<p>When you checkout a commit <code>git<\/code> materializes the code into the directory where\nthe repository is cloned and your local directory is made to match the tree of\nthe commit.  Thus, it is logically impossible to have more than one commit\nchecked out at once.  However, it can be extremely useful to have more than one\ncommit checked out at once if you are working on a project with multiple &ldquo;live&rdquo;\nbranches.  One way around this is to simply clone the repository N times,\nhowever because each repository is unaware of the other, you will have N\ncomplete copies of the repository and each will have to synchronized with their\nremotes independently, etc.  To make this efficient you can use the <code>git\nworktree<\/code> <a href=\"https:\/\/git-scm.com\/docs\/git-worktree\">sub-command<\/a><\/p>\n<div class=\"highlight\"><pre><span><\/span><code>git<span class=\"w\"> <\/span>worktree<span class=\"w\"> <\/span>add<span class=\"w\"> <\/span>..\/somepath<span class=\"w\"> <\/span>branch_name\n<\/code><\/pre><\/div>\n\n<p>This will share all of the <code>git<\/code> resources and configuration with the main\n<code>git<\/code> worktree.  One surprising limitation of the worktrees is that you can\nonly have a given branch checked out in at most one worktree at a time.<\/p>\n<h2 id=\"git-config\">git config<\/h2>\n<p>There are many (many) knobs to configure the default behavior.  I suggest using\nstarting with these settings:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">[transfer]<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\"># actually verify the hashes<\/span>\n<span class=\"w\">    <\/span><span class=\"na\">fsckobjects<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">true<\/span>\n<span class=\"k\">[fetch]<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\"># actually verify the hashes<\/span>\n<span class=\"w\">    <\/span><span class=\"na\">fsckobjects<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">true<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\"># automatically drop branches that are deleted on the remotes<\/span>\n<span class=\"w\">    <\/span><span class=\"na\">prune<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">true<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\"># fetch remotes in parallel<\/span>\n<span class=\"w\">    <\/span><span class=\"na\">parallel<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">0<\/span>\n<span class=\"k\">[receive]<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\"># actually verify the hashes<\/span>\n<span class=\"w\">    <\/span><span class=\"na\">fsckObjects<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">true<\/span>\n<span class=\"k\">[pull]<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\"># requires opting-into creating a merge commit locally.<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\"># Given a platform based workflow, this prevents unintentional merge<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\"># commits that need to be un-wound<\/span>\n<span class=\"w\">    <\/span><span class=\"na\">ff<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">only<\/span>\n<span class=\"k\">[merge]<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\"># same as above<\/span>\n<span class=\"w\">    <\/span><span class=\"na\">ff<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">only<\/span>\n<span class=\"k\">[color]<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\"># colours are always fun<\/span>\n<span class=\"w\">    <\/span><span class=\"na\">ui<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">auto<\/span>\n<span class=\"k\">[init]<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\"># get ahead of the master -&gt; main change<\/span>\n<span class=\"w\">    <\/span><span class=\"na\">defaultBranch<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">main<\/span>\n<span class=\"k\">[feature]<\/span>\n<span class=\"w\">    <\/span><span class=\"na\">manyFiles<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">true<\/span>\n<span class=\"k\">[alias]<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\"># this gives `git credit` as an alternative to `git blame`, just<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\"># puts you in a more positive mind set while using it.<\/span>\n<span class=\"w\">    <\/span><span class=\"na\">credit<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">blame<\/span>\n<\/code><\/pre><\/div>\n\n<h2 id=\"other-things-you-might-want-to-do\">Other things you might want to do<\/h2>\n<p>There are obviously many things that <code>git<\/code> can do that are not covered here.\nSome things that I have had to do from time-to-time but did not make the cut\nfor this article include:<\/p>\n<ul>\n<li>track the history of a line of code back in time (<code>gitk<\/code>, <code>git blame<\/code> + UI tooling, <code>git log<\/code>)<\/li>\n<li>find the commit that broke something (<code>git bisect<\/code>)<\/li>\n<li>merge un-related git histories into one (<code>git merge --allow-unrelated-histories<\/code>)<\/li>\n<li>extract the history of a sub-directory into its own repository (<code>git filter-branch<\/code>)<\/li>\n<li>purge a particular file (or change) from the history (<code>git filter-branch<\/code> or\n  <a href=\"https:\/\/rtyley.github.io\/bfg-repo-cleaner\/\">BFG repo-cleaner<\/a>)<\/li>\n<li>fast searching (<code>git grep<\/code>)<\/li>\n<li>ask <code>git<\/code> to clean up after itself (<code>git gc<\/code>)<\/li>\n<\/ul>\n<h2 id=\"other-resources\">Other resources<\/h2>\n<ul>\n<li><a href=\"https:\/\/ohshitgit.com\/\">recovering from git mistakes<\/a> (<a href=\"https:\/\/dangitgit.com\/en\">worksafe\n  version<\/a>): A humorous (and vulgar) guide to\n  recovering when things go wrong.<\/li>\n<li><a href=\"https:\/\/jvns.ca\/blog\/2018\/10\/27\/new-zine--oh-shit--git-\/\">Julia Evans on git<\/a><\/li>\n<li><a href=\"https:\/\/tom.preston-werner.com\/2009\/05\/19\/the-git-parable.html\">the Git\n  Parable<\/a>: A\n  just-so story that takes you from making backups by hand to agreeing with\n  some of the more mystifying choices git makes.<\/li>\n<li><a href=\"https:\/\/devblogs.microsoft.com\/search?query=git&amp;blog=%2Foldnewthing%2F\">Anything Raymond\n  Chen<\/a>\n  has written about git.  Some of these are just mind bending, like <a href=\"https:\/\/devblogs.microsoft.com\/oldnewthing\/20190510-00\/?p=102488\">Mundane\n  git commit-tree trick, Part 5: Squashing without git\n  rebase<\/a><\/li>\n<li>Git internals <a href=\"https:\/\/git-scm.com\/book\/en\/v2\/Git-Internals-Plumbing-and-Porcelain\">straight from the horse&rsquo;s\n  mouth<\/a>.<\/li>\n<li><a href=\"https:\/\/github.blog\/2020-12-17-commits-are-snapshots-not-diffs\/\">Commits are snapshots not diffs<\/a><\/li>\n<\/ul>\n<h2 id=\"acknowledgments\">Acknowledgments<\/h2>\n<p>Thank you to James Powell, Alex Held, Dora Caswell and the other beta-readers\nwho read (or listened to) early drafts of this post and provided valuable\nfeedback.  Thank you to Elliott Sales de Andrade for pointing out <code>git restore<\/code>.<\/p>","category":[{"@attributes":{"term":"Software Development"}},{"@attributes":{"term":"software"}},{"@attributes":{"term":"git"}}]},{"title":"Why I am fanatical about version control","link":{"@attributes":{"href":"https:\/\/tacaswell.github.io\/how-i-learned-to-love-vcs.html","rel":"alternate"}},"published":"2022-05-09T23:00:00-04:00","updated":"2022-05-25T00:55:00-04:00","author":{"name":"Thomas A Caswell"},"id":"tag:tacaswell.github.io,2022-05-09:\/how-i-learned-to-love-vcs.html","summary":"<p>A short horror story that could have been prevented by git.<\/p>","content":"<p>So, there I was.  The year was 2007 and I was in the process of wrapping up the\nresearch I had done as an undergraduate.  One of my tasks before heading off to\ngrad school was to archive all of the code I had written over the last two or\nso years to <a href=\"https:\/\/en.wikipedia.org\/wiki\/DVD%C2%B1R\">DVD-R<\/a> for the lab\narchive.<\/p>\n<p>My <a href=\"https:\/\/www.gnu.org\/software\/emacs\/\">editor<\/a> writes temporary backup copies\nwhile editing to the filename with a <code>~<\/code> appended.  Thus, for every source file\n<code>foo.m<\/code> I had been working on there was a paired <code>foo.m~<\/code> in the directory.  At\nthe time I was working in MATLAB and as was the convention had all off my\nsource in one directory.  This was the code that I used to generate the figures\nin my senior thesis and &ndash; more critically &ndash; the figures of <a href=\"https:\/\/www.sciencedirect.com\/science\/article\/abs\/pii\/S0304399108003264\">a paper we had in\npreparation<\/a> which\nwould require further revision.  Not wanting to archive transitory and\nduplicate files I happily typed<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nb\">cd<\/span><span class=\"w\"> <\/span>all\/of\/my-source\nrm<span class=\"w\"> <\/span>*<span class=\"w\"> <\/span>~\n<\/code><\/pre><\/div>\n\n<p>which very efficiently deleted all of the code I had written over the last two\nyears (&ldquo;Computers: making mistakes faster than you possibly imagined!&rdquo;).<\/p>\n<p>I did want any reasonable person would do and spent the next five minutes lying\non the floor trying to stave off a panic attack.<\/p>\n<p>In this particular case I was got stupendously lucky.  I had every file open in\nan editor and was able to go through and systematically add a space and re-save\nall of them.  From then on, everything I have written that looks like text that\nI suspect I may want to keep is very quickly committed into a version control\nsystem and distributed to at least two computers.<\/p>","category":[{"@attributes":{"term":"Software Development"}},{"@attributes":{"term":"software"}},{"@attributes":{"term":"git"}}]}]}