http://nvie.com/ nvie.com 2015-07-21T00:00:00+00:00 Vincent Driessen me@nvie.com http://nvie.com/about/ iron http://nvie.com/posts/writing-a-cli-in-python-in-under-60-seconds/ Writing a Command-Line Tool in Python 2014-09-24T00:00:00+00:00 <p>I used to find writing command line tools tedious. Not so much the writing of the core of the tool itself, but all the peripheral stuff you had to do to actually <em>finish</em> one.</p> <h3 id="the-language">The Language? <a href="#the-language" rel="bookmark" class="permalink">¶</a></h3> <p>The first issue is to pick the language to implement it in: do I use Python, which I'm intimitely familiar with, or a Unix shell script? With shell scripts, the syntax is pretty terrible, but the tool typically fits in a single file and there's hardly any overhead running them. On the other hand, making sure the tool works under all circumstances can be tricky. Shell scripts are notorious for breaking when you feed them arguments with spaces. The burden of making sure you properly quote all the variable interpolations in the script is on the programmer. It's possible to do, just unnecessarily hard.</p> <p>On the other hand, Python is so much more expressive. There are a ton of libraries out there ready to use, and Python itself includes a lot of batteries already in its standard library, of course.</p> <h3 id="distribution">Distribution? <a href="#distribution" rel="bookmark" class="permalink">¶</a></h3> <p>Python comes with its own set of problems, though. Python runtime environments are typically a mess, and I don't want to further pollute people's already cluttered global Python environments. With Python, installing a package is typically just a <code>pip install &lt;pkg&gt;</code> away, but it requires another tedious step: writing a <code>setup.py</code>.</p> <p>If it comes to distributing the script, a shell script may be much easier. With shell scripts it's either a single file that needs to be copied somewhere. Manually, or via a <code>make install</code> command, which involves adding a <code>Makefile</code> and dealing with subtle differences for each Unix platform, not to even mention trying to run it on Windows machines.</p> <h3 id="argument-parsing">Argument Parsing? <a href="#argument-parsing" rel="bookmark" class="permalink">¶</a></h3> <p>Each script will at some stage require some options or arguments. How should we do the argument parsing? Do I use <code>getopt</code> or <code>getopts</code>? Does it even matter? Can it take <code>--long-form-options</code>? Or do I resign myself to poor man's arg parsing again? The latter has too often become the default choice.</p> <h2 id="standing-on-the-shoulders-of-giants">Standing on the Shoulders of Giants <a href="#standing-on-the-shoulders-of-giants" rel="bookmark" class="permalink">¶</a></h2> <p>Lately, a few fantastic projects have taken away most of the tedious work surrounding the building of command line tools, and almost make it trivial now.</p> <h3 id="click">Click <a href="#click" rel="bookmark" class="permalink">¶</a></h3> <p><a href="http://click.pocoo.org">Click</a> is a Python library written by <a href="https://twitter.com/mitsuhiko">Armin Ronacher</a> that deals with all the handling of command line option and argument parsing and comes with fantastic defaults. This project is a great step towards more consistent and standard CLI interfaces. Besides solving the options and argument parsing, it also has a ton of useful features packaged, like smart colorized terminal output, file abstractions, subcommands, and rendering progress bars.</p> <p>It solves the argument parsing problem.</p> <h3 id="pipsi">pipsi <a href="#pipsi" rel="bookmark" class="permalink">¶</a></h3> <p>Using <a href="https://github.com/mitsuhiko/pipsi#readme">pipsi</a> (also by Armin!), users can install any Python command line script into an isolated Python runtime environment, so it solves the global cluttered Python environment problem entirely.</p> <h3 id="cookiecutter">Cookiecutter <a href="#cookiecutter" rel="bookmark" class="permalink">¶</a></h3> <p><a href="http://cookiecutter.readthedocs.org">Cookiecutter</a> (by the awesome <a href="https://twitter.com/audreyr">Audrey Roy Greenfield</a>) is a project generator, based on a predefined project template. It will read the template, ask the user a few questions to fill in the blanks, and generates a new project for you.</p> <h3 id="cookiecutter-python-cli">cookiecutter-python-cli <a href="#cookiecutter-python-cli" rel="bookmark" class="permalink">¶</a></h3> <p><a href="https://github.com/nvie/cookiecutter-python-cli">cookiecutter-python-cli</a> is one such Cookiecutter template I wrote that uses all of the above: it sports a predefined <code>setup.py</code>, a package structure that's extensible, and test cases and a test runner to get you started.</p> <h2 id="putting-it-together">Putting it Together <a href="#putting-it-together" rel="bookmark" class="permalink">¶</a></h2> <p>Let's build a new high quality CLI in Python in under 60 seconds now.</p> <p>First, install <a href="https://github.com/mitsuhiko/pipsi#readme">pipsi</a> and follow its instructions:</p> <div class="codehilite"><pre><span class="gp">$</span> curl https://raw.githubusercontent.com/mitsuhiko/pipsi/master/get-pipsi.py <span class="p">|</span> python </pre></div> <p>Next, using pipsi, install <a href="http://cookiecutter.readthedocs.org">Cookiecutter</a> in its own isolated runtime environment:</p> <div class="codehilite"><pre><span class="gp">$</span> pipsi install cookiecutter </pre></div> <p>Now use Cookiecutter to create your brand new project, based on my CLI template:</p> <div class="codehilite"><pre><span class="gp">$</span> <span class="nb">cd</span> ~/Desktop <span class="gp">$</span> cookiecutter https://github.com/nvie/cookiecutter-python-cli.git <span class="go">Cloning into &#39;cookiecutter-python-cli&#39;...</span> <span class="go">remote: Counting objects: 64, done.</span> <span class="go">remote: Total 64 (delta 0), reused 0 (delta 0)</span> <span class="go">Unpacking objects: 100% (64/64), done.</span> <span class="go">Checking connectivity... done.</span> <span class="go">full_name (default is &quot;Vincent Driessen&quot;)?</span> <span class="go">email (default is &quot;vincent@3rdcloud.com&quot;)?</span> <span class="go">github_username (default is &quot;nvie&quot;)?</span> <span class="go">project_name (default is &quot;My Tool&quot;)?</span> <span class="go">repo_name (default is &quot;python-mytool&quot;)?</span> <span class="go">pypi_name (default is &quot;mytool&quot;)?</span> <span class="go">script_name (default is &quot;my-tool&quot;)?</span> <span class="go">package_name (default is &quot;my_tool&quot;)?</span> <span class="go">project_short_description (default is &quot;My Tool does one thing, and one thing well.&quot;)?</span> <span class="go">release_date (default is &quot;2014-09-04&quot;)?</span> <span class="go">year (default is &quot;2014&quot;)?</span> <span class="go">version (default is &quot;0.1.0&quot;)?</span> </pre></div> <p>When you're done, you'll have a project where you can run <a href="https://testrun.org/tox"><code>tox</code></a> to run your test suite on all important Python versions. If you don't need the test cases, simply remove the <code>tests/</code> directory.</p> <div class="codehilite"><pre><span class="gp">$</span> <span class="nb">cd </span>python-mytool/ <span class="gp">$</span> tox <span class="go">...</span> <span class="go"> py26: commands succeeded</span> <span class="go"> py27: commands succeeded</span> <span class="go"> py33: commands succeeded</span> <span class="go"> py34: commands succeeded</span> <span class="go"> pypy: commands succeeded</span> <span class="go"> flake8: commands succeeded</span> <span class="go"> congratulations :)</span> </pre></div> <p>Let's install and run it without further modifications:</p> <div class="codehilite"><pre><span class="gp">$</span> pipsi install --editable . <span class="go">...</span> <span class="gp">$</span> my-tool <span class="go">Hello, world.</span> <span class="gp">$</span> my-tool --as-cowboy <span class="go">Howdy, world.</span> <span class="gp">$</span> my-tool --as-cowboy Vincent <span class="go">Howdy, Vincent.</span> </pre></div> <p>You can edit the <code>setup.py</code> to your liking. The default provided version should already work out of the box. When you're done implementing your tool, you can either upload it to PyPI or just keep it to yourself locally:</p> <div class="codehilite"><pre><span class="gp">$</span> pipsi install &lt;pkgname&gt; <span class="c"># install from PyPI</span> <span class="gp">$</span> pipsi install --editable ../path/to/project/dir <span class="c"># install locally</span> </pre></div> <p>If you have any improvements for this template, please submit <a href="https://github.com/nvie/cookiecutter-python-cli/pulls">a pull request</a>. Thanks!</p> I used to find writing command line tools tedious. Not so much the writing of the core of the tool itself, but all the peripheral stuff you had to do to actually _finish_ one. 2014-09-24T00:00:00+00:00 http://nvie.com/posts/a-successful-git-branching-model/ A successful Git branching model 2010-01-05T00:00:00+00:00 <p>In this post I present the development model that I’ve introduced for all of my projects (both at work and private) about a year ago, and which has turned out to be very successful. I’ve been meaning to write about it for a while now, but I’ve never really found the time to do so thoroughly, until now. I won’t talk about any of the projects’ details, merely about the branching strategy and release management.</p> <p class="centered"><img alt="" src="/img/git-model@2x.png" width="575" /></p> <p>It focuses around <a href="http://git-scm.com">Git</a> as the tool for the versioning of all of our source code.</p> <h2 id="why-git">Why git? <a href="#why-git" rel="bookmark" class="permalink">¶</a></h2> <p>For a thorough discussion on the pros and cons of Git compared to centralized source code control systems, <a href="http://whygitisbetterthanx.com/">see</a> the <a href="http://git.or.cz/gitwiki/GitSvnComparsion">web</a>. There are plenty of flame wars going on there. As a developer, I prefer Git above all other tools around today. Git really changed the way developers think of merging and branching. From the classic CVS/Subversion world I came from, merging/branching has always been considered a bit scary (“beware of merge conflicts, they bite you!”) and something you only do every once in a while.</p> <p>But with Git, these actions are extremely cheap and simple, and they are considered one of the core parts of your <em>daily</em> workflow, really. For example, in CVS/Subversion <a href="http://svnbook.red-bean.com">books</a>, branching and merging is first discussed in the later chapters (for advanced users), while in <a href="http://book.git-scm.com">every</a> <a href="http://pragprog.com/titles/tsgit/pragmatic-version-control-using-git">Git</a> <a href="http://github.com/progit/progit">book</a>, it’s already covered in chapter 3 (basics).</p> <p>As a consequence of its simplicity and repetitive nature, branching and merging are no longer something to be afraid of. Version control tools are supposed to assist in branching/merging more than anything else.</p> <p>Enough about the tools, let’s head onto the development model. The model that I’m going to present here is essentially no more than a set of procedures that every team member has to follow in order to come to a managed software development process.</p> <h2 id="decentralized-but-centralized">Decentralized but centralized <a href="#decentralized-but-centralized" rel="bookmark" class="permalink">¶</a></h2> <p>The repository setup that we use and that works well with this branching model, is that with a central “truth” repo. Note that this repo is only <em>considered</em> to be the central one (since Git is a DVCS, there is no such thing as a central repo at a technical level). We will refer to this repo as <code>origin</code>, since this name is familiar to all Git users.</p> <p class="centered"><img alt="" src="/img/centr-decentr@2x.png" width="487" /></p> <p>Each developer pulls and pushes to origin. But besides the centralized push-pull relationships, each developer may also pull changes from other peers to form sub teams. For example, this might be useful to work together with two or more developers on a big new feature, before pushing the work in progress to <code>origin</code> prematurely. In the figure above, there are subteams of Alice and Bob, Alice and David, and Clair and David.</p> <p>Technically, this means nothing more than that Alice has defined a Git remote, named <code>bob</code>, pointing to Bob’s repository, and vice versa.</p> <h2 id="the-main-branches">The main branches <a href="#the-main-branches" rel="bookmark" class="permalink">¶</a></h2> <p><img alt="" class="right" src="/img/main-branches@2x.png" width="267" /></p> <p>At the core, the development model is greatly inspired by existing models out there. The central repo holds two main branches with an infinite lifetime:</p> <ul> <li><code>master</code></li> <li><code>develop</code></li> </ul> <p>The <code>master</code> branch at <code>origin</code> should be familiar to every Git user. Parallel to the <code>master</code> branch, another branch exists called <code>develop</code>.</p> <p>We consider <code>origin/master</code> to be the main branch where the source code of <code>HEAD</code> always reflects a <em>production-ready</em> state.</p> <p>We consider <code>origin/develop</code> to be the main branch where the source code of <code>HEAD</code> always reflects a state with the latest delivered development changes for the next release. Some would call this the “integration branch”. This is where any automatic nightly builds are built from.</p> <p>When the source code in the <code>develop</code> branch reaches a stable point and is ready to be released, all of the changes should be merged back into <code>master</code> somehow and then tagged with a release number. How this is done in detail will be discussed further on.</p> <p>Therefore, each time when changes are merged back into <code>master</code>, this is a new production release <em>by definition</em>. We tend to be very strict at this, so that theoretically, we could use a Git hook script to automatically build and roll-out our software to our production servers everytime there was a commit on <code>master</code>.</p> <h2 id="supporting-branches">Supporting branches <a href="#supporting-branches" rel="bookmark" class="permalink">¶</a></h2> <p>Next to the main branches <code>master</code> and <code>develop</code>, our development model uses a variety of supporting branches to aid parallel development between team members, ease tracking of features, prepare for production releases and to assist in quickly fixing live production problems. Unlike the main branches, these branches always have a limited life time, since they will be removed eventually.</p> <p>The different types of branches we may use are:</p> <ul> <li>Feature branches</li> <li>Release branches</li> <li>Hotfix branches</li> </ul> <p>Each of these branches have a specific purpose and are bound to strict rules as to which branches may be their originating branch and which branches must be their merge targets. We will walk through them in a minute.</p> <p>By no means are these branches “special” from a technical perspective. The branch types are categorized by how we <em>use</em> them. They are of course plain old Git branches.</p> <h3 id="feature-branches">Feature branches <a href="#feature-branches" rel="bookmark" class="permalink">¶</a></h3> <p><img alt="" class="right" src="/img/fb@2x.png" width="133" /></p> <dl> <dt>May branch off from:</dt> <dd><code>develop</code> </dd> <dt>Must merge back into:</dt> <dd><code>develop</code> </dd> <dt>Branch naming convention:</dt> <dd>anything except <code>master</code>, <code>develop</code>, <code>release-*</code>, or <code>hotfix-*</code></dd> </dl> <p>Feature branches (or sometimes called topic branches) are used to develop new features for the upcoming or a distant future release. When starting development of a feature, the target release in which this feature will be incorporated may well be unknown at that point. The essence of a feature branch is that it exists as long as the feature is in development, but will eventually be merged back into <code>develop</code> (to definitely add the new feature to the upcoming release) or discarded (in case of a disappointing experiment).</p> <p>Feature branches typically exist in developer repos only, not in <code>origin</code>.</p> <h4 id="creating-a-feature-branch">Creating a feature branch <a href="#creating-a-feature-branch" rel="bookmark" class="permalink">¶</a></h4> <p>When starting work on a new feature, branch off from the <code>develop</code> branch.</p> <div class="codehilite"><pre><span class="gp">$</span> git checkout -b myfeature develop <span class="go">Switched to a new branch &quot;myfeature&quot;</span> </pre></div> <h4 id="incorporating-a-finished-feature-on-develop">Incorporating a finished feature on develop <a href="#incorporating-a-finished-feature-on-develop" rel="bookmark" class="permalink">¶</a></h4> <p>Finished features may be merged into the <code>develop</code> branch definitely add them to the upcoming release:</p> <div class="codehilite"><pre><span class="gp">$</span> git checkout develop <span class="go">Switched to branch &#39;develop&#39;</span> <span class="gp">$</span> git merge --no-ff myfeature <span class="go">Updating ea1b82a..05e9557</span> <span class="go">(Summary of changes)</span> <span class="gp">$</span> git branch -d myfeature <span class="go">Deleted branch myfeature (was 05e9557).</span> <span class="gp">$</span> git push origin develop </pre></div> <p>The <code>--no-ff</code> flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature. Compare:</p> <p class="centered"><img alt="" src="/img/merge-without-ff@2x.png" width="478" /></p> <p>In the latter case, it is impossible to see from the Git history which of the commit objects together have implemented a feature—you would have to manually read all the log messages. Reverting a whole feature (i.e. a group of commits), is a true headache in the latter situation, whereas it is easily done if the <code>--no-ff</code> flag was used.</p> <p>Yes, it will create a few more (empty) commit objects, but the gain is much bigger that that cost.</p> <p>Unfortunately, I have not found a way to make <code>--no-ff</code> the default behaviour of <code>git merge</code> yet, but it really should be.</p> <h3 id="release-branches">Release branches <a href="#release-branches" rel="bookmark" class="permalink">¶</a></h3> <dl> <dt>May branch off from:</dt> <dd><code>develop</code></dd> <dt>Must merge back into:</dt> <dd><code>develop</code> and <code>master</code></dd> <dt>Branch naming convention:</dt> <dd><code>release-*</code></dd> </dl> <p>Release branches support preparation of a new production release. They allow for last-minute dotting of i’s and crossing t’s. Furthermore, they allow for minor bug fixes and preparing meta-data for a release (version number, build dates, etc.). By doing all of this work on a release branch, the <code>develop</code> branch is cleared to receive features for the next big release.</p> <p>The key moment to branch off a new release branch from <code>develop</code> is when develop (almost) reflects the desired state of the new release. At least all features that are targeted for the release-to-be-built must be merged in to <code>develop</code> at this point in time. All features targeted at future releases may not—they must wait until after the release branch is branched off.</p> <p>It is exactly at the start of a release branch that the upcoming release gets assigned a version number—not any earlier. Up until that moment, the <code>develop</code> branch reflected changes for the “next release”, but it is unclear whether that “next release” will eventually become 0.3 or 1.0, until the release branch is started. That decision is made on the start of the release branch and is carried out by the project’s rules on version number bumping.</p> <h4 id="creating-a-release-branch">Creating a release branch <a href="#creating-a-release-branch" rel="bookmark" class="permalink">¶</a></h4> <p>Release branches are created from the <code>develop</code> branch. For example, say version 1.1.5 is the current production release and we have a big release coming up. The state of <code>develop</code> is ready for the “next release” and we have decided that this will become version 1.2 (rather than 1.1.6 or 2.0). So we branch off and give the release branch a name reflecting the new version number:</p> <div class="codehilite"><pre><span class="gp">$</span> git checkout -b release-1.2 develop <span class="go">Switched to a new branch &quot;release-1.2&quot;</span> <span class="gp">$</span> ./bump-version.sh 1.2 <span class="go">Files modified successfully, version bumped to 1.2.</span> <span class="gp">$</span> git commit -a -m <span class="s2">&quot;Bumped version number to 1.2&quot;</span> <span class="go">[release-1.2 74d9424] Bumped version number to 1.2</span> <span class="go">1 files changed, 1 insertions(+), 1 deletions(-)</span> </pre></div> <p>After creating a new branch and switching to it, we bump the version number. Here, <code>bump-version.sh</code> is a fictional shell script that changes some files in the working copy to reflect the new version. (This can of course be a manual change—the point being that <em>some</em> files change.) Then, the bumped version number is committed.</p> <p>This new branch may exist there for a while, until the release may be rolled out definitely. During that time, bug fixes may be applied in this branch (rather than on the <code>develop</code> branch). Adding large new features here is strictly prohibited. They must be merged into <code>develop</code>, and therefore, wait for the next big release.</p> <h4 id="finishing-a-release-branch">Finishing a release branch <a href="#finishing-a-release-branch" rel="bookmark" class="permalink">¶</a></h4> <p>When the state of the release branch is ready to become a real release, some actions need to be carried out. First, the release branch is merged into <code>master</code> (since every commit on <code>master</code> is a new release <em>by definition</em>, remember). Next, that commit on <code>master</code> must be tagged for easy future reference to this historical version. Finally, the changes made on the release branch need to be merged back into <code>develop</code>, so that future releases also contain these bug fixes.</p> <p>The first two steps in Git:</p> <div class="codehilite"><pre><span class="gp">$</span> git checkout master <span class="go">Switched to branch &#39;master&#39;</span> <span class="gp">$</span> git merge --no-ff release-1.2 <span class="go">Merge made by recursive.</span> <span class="go">(Summary of changes)</span> <span class="gp">$</span> git tag -a 1.2 </pre></div> <p>The release is now done, and tagged for future reference. </p> <blockquote> <p><strong>Edit:</strong> You might as well want to use the <code>-s</code> or <code>-u &lt;key&gt;</code> flags to sign your tag cryptographically.</p> </blockquote> <p>To keep the changes made in the release branch, we need to merge those back into <code>develop</code>, though. In Git:</p> <div class="codehilite"><pre><span class="gp">$</span> git checkout develop <span class="go">Switched to branch &#39;develop&#39;</span> <span class="gp">$</span> git merge --no-ff release-1.2 <span class="go">Merge made by recursive.</span> <span class="go">(Summary of changes)</span> </pre></div> <p>This step may well lead to a merge conflict (probably even, since we have changed the version number). If so, fix it and commit.</p> <p>Now we are really done and the release branch may be removed, since we don’t need it anymore:</p> <div class="codehilite"><pre><span class="gp">$</span> git branch -d release-1.2 <span class="go">Deleted branch release-1.2 (was ff452fe).</span> </pre></div> <h3 id="hotfix-branches">Hotfix branches <a href="#hotfix-branches" rel="bookmark" class="permalink">¶</a></h3> <p><img alt="" class="right" src="/img/hotfix-branches@2x.png" width="316" /></p> <dl> <dt>May branch off from:</dt> <dd><code>master</code></dd> <dt>Must merge back into:</dt> <dd><code>develop</code> and <code>master</code></dd> <dt>Branch naming convention:</dt> <dd><code>hotfix-*</code></dd> </dl> <p>Hotfix branches are very much like release branches in that they are also meant to prepare for a new production release, albeit unplanned. They arise from the necessity to act immediately upon an undesired state of a live production version. When a critical bug in a production version must be resolved immediately, a hotfix branch may be branched off from the corresponding tag on the master branch that marks the production version.</p> <p>The essence is that work of team members (on the <code>develop</code> branch) can continue, while another person is preparing a quick production fix.</p> <h4 id="creating-the-hotfix-branch">Creating the hotfix branch <a href="#creating-the-hotfix-branch" rel="bookmark" class="permalink">¶</a></h4> <p>Hotfix branches are created from the <code>master</code> branch. For example, say version 1.2 is the current production release running live and causing troubles due to a severe bug. But changes on <code>develop</code> are yet unstable. We may then branch off a hotfix branch and start fixing the problem:</p> <div class="codehilite"><pre><span class="gp">$</span> git checkout -b hotfix-1.2.1 master <span class="go">Switched to a new branch &quot;hotfix-1.2.1&quot;</span> <span class="gp">$</span> ./bump-version.sh 1.2.1 <span class="go">Files modified successfully, version bumped to 1.2.1.</span> <span class="gp">$</span> git commit -a -m <span class="s2">&quot;Bumped version number to 1.2.1&quot;</span> <span class="go">[hotfix-1.2.1 41e61bb] Bumped version number to 1.2.1</span> <span class="go">1 files changed, 1 insertions(+), 1 deletions(-)</span> </pre></div> <p>Don’t forget to bump the version number after branching off!</p> <p>Then, fix the bug and commit the fix in one or more separate commits.</p> <div class="codehilite"><pre><span class="gp">$</span> git commit -m <span class="s2">&quot;Fixed severe production problem&quot;</span> <span class="go">[hotfix-1.2.1 abbe5d6] Fixed severe production problem</span> <span class="go">5 files changed, 32 insertions(+), 17 deletions(-)</span> </pre></div> <p><strong>Finishing a hotfix branch</strong></p> <p>When finished, the bugfix needs to be merged back into <code>master</code>, but also needs to be merged back into <code>develop</code>, in order to safeguard that the bugfix is included in the next release as well. This is completely similar to how release branches are finished.</p> <p>First, update <code>master</code> and tag the release.</p> <div class="codehilite"><pre><span class="gp">$</span> git checkout master <span class="go">Switched to branch &#39;master&#39;</span> <span class="gp">$</span> git merge --no-ff hotfix-1.2.1 <span class="go">Merge made by recursive.</span> <span class="go">(Summary of changes)</span> <span class="gp">$</span> git tag -a 1.2.1 </pre></div> <p><strong>Edit:</strong> You might as well want to use the <code>-s</code> or <code>-u &lt;key&gt;</code> flags to sign your tag cryptographically.</p> <p>Next, include the bugfix in <code>develop</code>, too:</p> <div class="codehilite"><pre><span class="gp">$</span> git checkout develop <span class="go">Switched to branch &#39;develop&#39;</span> <span class="gp">$</span> git merge --no-ff hotfix-1.2.1 <span class="go">Merge made by recursive.</span> <span class="go">(Summary of changes)</span> </pre></div> <p>The one exception to the rule here is that, <strong>when a release branch currently exists, the hotfix changes need to be merged into that release branch, instead of <code>develop</code></strong>. Back-merging the bugfix into the release branch will eventually result in the bugfix being merged into <code>develop</code> too, when the release branch is finished. (If work in <code>develop</code> immediately requires this bugfix and cannot wait for the release branch to be finished, you may safely merge the bugfix into <code>develop</code> now already as well.)</p> <p>Finally, remove the temporary branch:</p> <div class="codehilite"><pre><span class="gp">$</span> git branch -d hotfix-1.2.1 <span class="go">Deleted branch hotfix-1.2.1 (was abbe5d6).</span> </pre></div> <h2 id="summary">Summary <a href="#summary" rel="bookmark" class="permalink">¶</a></h2> <p>While there is nothing really shocking new to this branching model, the “big picture” figure that this post began with has turned out to be tremendously useful in our projects. It forms an elegant mental model that is easy to comprehend and allows team members to develop a shared understanding of the branching and releasing processes.</p> <p>A high-quality PDF version of the figure is provided here. Go ahead and hang it on the wall for quick reference at any time.</p> <p><strong>Update:</strong> And for anyone who requested it: here’s the <a href="http://github.com/downloads/nvie/gitflow/Git-branching-model-src.key.zip">gitflow-model.src.key</a> of the main diagram image (Apple Keynote).</p> <p class="centered"><a href="/files/Git-branching-model.pdf"><img alt="" src="/img/pdf@2x.png" width="128" /></a><br /> <a href="/files/Git-branching-model.pdf">Git-branching-model.pdf</a></p> In this post I present a Git branching strategy for developing and releasing software as I’ve used it in many of my projects, and which has turned out to be very successful. 2010-01-05T00:00:00+00:00 http://nvie.com/posts/pip-tools-10-released/ pip-tools 1.0 released 2015-07-21T00:00:00+00:00 <p>Yesterday, pip-tools version 1.0 was silently released, officially introducing the <strong>pip-compile</strong> and <strong>pip-sync</strong> tools, and replacing the current <strong>pip-dump</strong> and <strong>pip-review</strong> tools.</p> <p>I've blogged before about these ideas in <a href="/posts/pin-your-packages">Pinning Your Packages</a> and <a href="/posts/better-package-management">Better Package Management</a>. During the last year, I've been slowly working on the future branch on the pip-tools repo, and have been using the new tools there. The <strong>pip-sync</strong> script was the only thing that was still delaying the release, but since <a href="https://github.com/hugopeixoto">Hugo Peixoto</a> <a href="https://github.com/nvie/pip-tools/pull/181">contributed</a> this one recently, it's now ready to switch over.</p> <p>So it's now time to switch over to the new tools if you've been using the old ones.</p> <p>Old: pip-review, pip-dump<br /> New: <strong>pip-compile</strong>, <strong>pip-sync</strong></p> <h2 id="how-to-upgrade">How to upgrade <a href="#how-to-upgrade" rel="bookmark" class="permalink">¶</a></h2> <p>If you're using pip-tools 0.x, you'll notice that its main commands, pip-review and pip-dump are gone. Instead, you'll find two new commands, pip-compile and pip-sync, which should allow you to do the same things, but arguably in a more solid way.</p> <p>Typical usage:</p> <ul> <li><code>pip install pip-tools</code></li> <li>Record your top-level dependencies in <code>requirements.in</code>. Everything you <em>directly</em> use in your source code should be a top-level dependency.</li> <li>Don't pin them—unless you want them pinned, of course.</li> <li>Put both <code>requirements.in</code> and <code>requirements.txt</code> under version control.</li> <li>Then, run pip-compile. This will produce a <code>requirements.txt</code> that pins the high-level requirements to the highest versions found on PyPI to match the given requirements.</li> <li>Using <code>pip-sync</code> now will install/upgrade/uninstall everything so that your virtual env exactly matches what's in <code>requirements.txt</code>.</li> </ul> <p>For more information, see the <a href="https://github.com/nvie/pip-tools#readme">README</a> of the new tools.</p> <p>Let me know how it works for you!</p> Yesterday, pip-tools version 1.0 was silently released, officially introducing the **pip-compile** and **pip-sync** tools, and replacing the current **pip-dump** and **pip-review** tools. 2015-07-21T00:00:00+00:00 http://nvie.com/posts/beautiful-code/ Beautiful Code 2015-06-16T00:00:00+00:00 <p>When was the last time you looked at code someone else wrote? (Debugging doens't count!) When did you <em>actually</em> study it to learn from it? Perhaps even ponder over its beauty?</p> <p>It's surprising <strong>how uncommon it is in our industry to look at existing code just to learn from it</strong>. In almost any other engineering or art field, people constantly study the results of their peers. Books on architecture are a great example. What makes a certain design so beautiful or effective? Can I learn something from it to make me a better engineer? I feel <strong>we would benefit as an industry if we would collectively take a little more time to reflect and study</strong>. We should ask ourselves those question more often, and allocate study time for it occasionally.</p> <p class="right"><img alt="The cover of Beautiful Code" height="300" src="/img/beautiful-code-cover@2x.jpg" /></p> <p>Last week, I ordered the book <a href="http://shop.oreilly.com/product/9780596510046.do">Beautiful Code</a>, by Greg Wilson and Andy Oram. I would recommend this book to any fellow professional programmer. (All of the book's proceeds go to Amnesty International.)</p> <p>The book's concept is simple: each of the 33 chapters is written by a well-respected professional programmer who answers the question: <em>"What is the most beautiful code you've ever seen?"</em> after which they discuss elaborately <em>why</em> they think it's beautiful.</p> <p>Beauty, as it turns out, comes in many shapes and forms. The topics in the book vary from an elegant algorithm, to a design that lets all the surrounding puzzle pieces fall into place perfectly. From the cleverness of code generators, to the expressiveness of a language construct.</p> <p>Naturally, some chapters have been more interesting than others. But all of them have left me with either:</p> <ul> <li>a deep admiration for an elegant solution or cleverness;</li> <li>an interesting perspective on good design;</li> <li>an appreciation of seemingly banal things, or things I previously did not find beauty in;</li> <li>insight into how to articulate <em>why</em> exactly something is beautiful (how meta)</li> </ul> When was the last time you looked at code someone else wrote? (Debugging doens't count!) When did you _actually_ study it to learn from it? Perhaps even ponder over its beauty? 2015-06-16T00:00:00+00:00 http://nvie.com/posts/beautiful-map/ Beautiful Map 2015-06-15T00:00:00+00:00 <p>I was reading Igor Kalnitsky's blog post on why Python's <a href="http://kalnitsky.org/2015/06/14/mad-map/"><code>map()</code> is mad</a>, and wanted to provide a different perspective. In fact, I would call the design of Python's <code>map()</code> beautiful instead.</p> <p>First off, what does <code>map(f, xs)</code> represent mathematically in the first place? It should invoke function <code>f(x)</code> for every <code>x</code> in <code>xs</code>. Functions, of course, can take many arguments—single argument functions are just the simplest case. So what would be reasonable to assume <code>map(f, xs, ys)</code> would do? In the blog post, Igor suggests the behaviour should be to chain <code>xs</code> and <code>ys</code>, but chances are they represent completely different things, so chaining them would lead to a heterogenous collection of items. Mathematically, you would expect the function calls made to be <code>f(x1, y1)</code>, <code>f(x2, y2)</code>, ...</p> <p>Note that this is <em>different</em> from <code>zip()</code>'ing the function arguments. A function <code>f</code> with 2 arguments is different from a function <code>f</code> with 1 argument, expecting a tuple.</p> <p>Compare:</p> <div class="codehilite"><pre><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span> <span class="k">return</span> <span class="n">x</span> <span class="o">*</span> <span class="n">y</span> <span class="nb">map</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="p">[</span><span class="s">&#39;a&#39;</span><span class="p">,</span> <span class="s">&#39;b&#39;</span><span class="p">,</span> <span class="s">&#39;c&#39;</span><span class="p">],</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">])</span> <span class="c"># [&#39;a&#39;, &#39;bb&#39;, &#39;ccc&#39;]</span> </pre></div> <p>to</p> <div class="codehilite"><pre><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">pair</span><span class="p">):</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">pair</span> <span class="k">return</span> <span class="n">x</span> <span class="o">*</span> <span class="n">y</span> <span class="nb">map</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="nb">zip</span><span class="p">([</span><span class="s">&#39;a&#39;</span><span class="p">,</span> <span class="s">&#39;b&#39;</span><span class="p">,</span> <span class="s">&#39;c&#39;</span><span class="p">],</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]))</span> <span class="c"># [&#39;a&#39;, &#39;bb&#39;, &#39;ccc&#39;]</span> </pre></div> <p>The confusion around the items appearing to be zipped is caused by the implicit behaviour in Python 2 when the first argument is <code>None</code>. I think it's handled as a special case, which is unfortunate. A more consistent behaviour would have been to</p> <div class="codehilite"><pre><span class="go">Python 2.7.9 (default, Dec 19 2014, 06:00:59)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span><span class="p">,</span> <span class="p">[</span><span class="s">&#39;a&#39;</span><span class="p">],</span> <span class="p">[</span><span class="mi">1</span><span class="p">])</span> <span class="gt">Traceback (most recent call last):</span> File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span> <span class="gr">TypeError</span>: <span class="n">&lt;lambda&gt;() takes exactly 1 argument (2 given)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">map</span><span class="p">(</span><span class="bp">None</span><span class="p">,</span> <span class="p">[</span><span class="s">&#39;a&#39;</span><span class="p">],</span> <span class="p">[</span><span class="mi">1</span><span class="p">])</span> <span class="go">[(&#39;a&#39;, 1)]</span> </pre></div> <p>The TypeError would have been the sane thing to do, since the identity function should only ever take one argument.</p> <p>Therefore, my advice would be to never use the implicit <code>None</code> as the first argument. It is broken under Python 3 anyway.</p> <h2 id="to-zip-or-to-zip_longest">To <code>zip()</code> or to <code>zip_longest()</code>? <a href="#to-zip-or-to-zip_longest" rel="bookmark" class="permalink">¶</a></h2> <p>The fact that the behaviour changed in Python 3 is unfortunate, but I think it changed for the better. The problem with <code>zip_longest()</code>-like default semantics is that it will only ever work with finite iterables. If only one of the given iterables is infinite, the map will be infinite too. Now, perhaps this is what you want, but in that case you should probably be explicit about it anyway. I think using <code>zip()</code>-like semantics as the default makes perfect sense. It enables the following usage in Python 3:</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">itertools</span> <span class="kn">import</span> <span class="n">count</span> <span class="gp">&gt;&gt;&gt; </span> <span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span> <span class="gp">... </span> <span class="k">return</span> <span class="n">x</span> <span class="o">*</span> <span class="n">y</span> <span class="gp">... </span> <span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">map</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="p">[</span><span class="s">&#39;a&#39;</span><span class="p">,</span> <span class="s">&#39;b&#39;</span><span class="p">,</span> <span class="s">&#39;c&#39;</span><span class="p">],</span> <span class="n">count</span><span class="p">(</span><span class="mi">1</span><span class="p">)):</span> <span class="gp">... </span> <span class="k">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="gp">...</span> <span class="go">a</span> <span class="go">bb</span> <span class="go">ccc</span> </pre></div> <p>Compare this to Python 2's map behaviour, which would do:</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">map</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="p">[</span><span class="s">&#39;a&#39;</span><span class="p">,</span> <span class="s">&#39;b&#39;</span><span class="p">,</span> <span class="s">&#39;c&#39;</span><span class="p">],</span> <span class="n">count</span><span class="p">(</span><span class="mi">1</span><span class="p">)):</span> <span class="gp">... </span> <span class="k">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="gp">...</span> <span class="go">a</span> <span class="go">bb</span> <span class="go">ccc</span> <span class="gt">Traceback (most recent call last):</span> File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span> File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">f</span> <span class="gr">TypeError</span>: <span class="n">unsupported operand type(s) for *: &#39;NoneType&#39; and &#39;int&#39;</span> </pre></div> <p>Because it tries to invoke <code>f(None, 4)</code> the fourth time, which happens to fail. If it would not fail, it would produce results infinitely.</p> <p>But what <em>if</em> you actually want <code>zip_longest()</code>-like behaviour? Well, you can either make all arguments be infinite iterables, or you can explicitly wrap your arguments in a <code>zip_longest()</code> wrapper, and pass that to <code>starmap()</code>, which will take an iterable of tuples and spread it over the arguments to <code>f()</code>, just like <code>map</code>:</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">itertools</span> <span class="kn">import</span> <span class="n">count</span><span class="p">,</span> <span class="n">islice</span><span class="p">,</span> <span class="n">starmap</span><span class="p">,</span> <span class="n">zip_longest</span> <span class="go">&gt;&gt;&gt;</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">result</span> <span class="o">=</span> <span class="n">starmap</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">zip_longest</span><span class="p">([</span><span class="s">&#39;a&#39;</span><span class="p">,</span> <span class="s">&#39;b&#39;</span><span class="p">,</span> <span class="s">&#39;c&#39;</span><span class="p">],</span> <span class="n">count</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span> <span class="n">fillvalue</span><span class="o">=</span><span class="s">&#39;?&#39;</span><span class="p">))</span> <span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">islice</span><span class="p">(</span><span class="n">result</span><span class="p">,</span> <span class="mi">7</span><span class="p">):</span> <span class="gp">... </span> <span class="k">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="gp">...</span> <span class="go">a</span> <span class="go">bb</span> <span class="go">ccc</span> <span class="go">????</span> <span class="go">?????</span> <span class="go">??????</span> <span class="go">???????</span> </pre></div> <p>As a bonus, you can pass in a fillvalue this way, instead of being stuck with the assumption of <code>None</code> (which could happen to be a valid value within the iterable).</p> <p>However, personally, in this case, I'd prefer the following, more readable version that avoids the <code>zip_longest()</code> and <code>starmap()</code> calls:</p> <div class="codehilite"><pre><span class="nb">map</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">chain</span><span class="p">([</span><span class="s">&#39;a&#39;</span><span class="p">,</span> <span class="s">&#39;b&#39;</span><span class="p">,</span> <span class="s">&#39;c&#39;</span><span class="p">],</span> <span class="n">repeat</span><span class="p">(</span><span class="s">&#39;?&#39;</span><span class="p">)),</span> <span class="n">count</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span> </pre></div> <p>Note how you can thus make the map result infinite by simply making all iterables infinite. Consuming iterables until the first one is exhausted (so <code>zip()</code>-like), thus, is the sanest default behaviour, and the most beautiful of the options.</p> <h2 id="python-3-gets-it-right">Python 3 gets it right <a href="#python-3-gets-it-right" rel="bookmark" class="permalink">¶</a></h2> <p>I'm glad that Python 3 changed <code>map()</code> to be sane in every way:</p> <ul> <li>It's made a lazy iterator, does not directly <a href="/posts/use-more-iterators/#composability">produce a list</a></li> <li>It disallows the ambiguous <code>None</code> first argument</li> <li>It consumes the iterables until the first one is exhausted.</li> </ul> <h2 id="bonus-your-own-zip">Bonus: your own <code>zip()</code> <a href="#bonus-your-own-zip" rel="bookmark" class="permalink">¶</a></h2> <p>Did you know you could express <code>zip()</code> with <code>map()</code>? It's easy, now you know the exact semantics:</p> <div class="codehilite"><pre><span class="k">def</span> <span class="nf">zip</span><span class="p">(</span><span class="o">*</span><span class="n">iterables</span><span class="p">):</span> <span class="k">return</span> <span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="o">*</span><span class="n">args</span><span class="p">:</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">args</span><span class="p">),</span> <span class="o">*</span><span class="n">iterables</span><span class="p">)</span> </pre></div> I was reading Igor Kalnitsky's blog post on why Python's [`map()` is mad](http://kalnitsky.org/2015/06/14/mad-map/), and wanted to provide a different perspective. In fact, I would call the design of Python's `map()` beautiful instead. 2015-06-15T00:00:00+00:00 http://nvie.com/posts/modifying-deeply-nested-structures/ Modifying Deeply-Nested Structures 2014-10-03T00:00:00+00:00 <p>Yesterday, a friend asked me how I would solve a certain problem he was facing. He did have a working solution, but felt like he could make it more generally applicable. Not shying away at a good challenge, I decided to take it and see how I would solve it. In this blog post you can read about my solution.</p> <h2 id="the-problem">The Problem <a href="#the-problem" rel="bookmark" class="permalink">¶</a></h2> <p>Consider this JSON document. Return the same JSON document, but with the points list sorted by stop time in descending order.</p> <div class="codehilite"><pre><span class="p">{</span> <span class="nt">&quot;timestamp&quot;</span><span class="p">:</span> <span class="mi">1412282459</span><span class="p">,</span> <span class="nt">&quot;res&quot;</span><span class="p">:</span> <span class="p">[</span> <span class="p">{</span> <span class="nt">&quot;group&quot;</span><span class="p">:</span> <span class="s2">&quot;1&quot;</span><span class="p">,</span> <span class="nt">&quot;catlist&quot;</span><span class="p">:</span> <span class="p">[</span> <span class="p">{</span> <span class="nt">&quot;cat&quot;</span><span class="p">:</span> <span class="s2">&quot;1&quot;</span><span class="p">,</span> <span class="nt">&quot;start&quot;</span><span class="p">:</span> <span class="s2">&quot;none&quot;</span><span class="p">,</span> <span class="nt">&quot;stop&quot;</span><span class="p">:</span> <span class="s2">&quot;none&quot;</span><span class="p">,</span> <span class="nt">&quot;points&quot;</span><span class="p">:</span> <span class="p">[</span> <span class="p">{</span><span class="nt">&quot;point&quot;</span><span class="p">:</span> <span class="s2">&quot;1&quot;</span><span class="p">,</span> <span class="nt">&quot;start&quot;</span><span class="p">:</span> <span class="s2">&quot;13.00&quot;</span><span class="p">,</span> <span class="nt">&quot;stop&quot;</span><span class="p">:</span> <span class="s2">&quot;13.35&quot;</span><span class="p">},</span> <span class="p">{</span><span class="nt">&quot;point&quot;</span><span class="p">:</span> <span class="s2">&quot;2&quot;</span><span class="p">,</span> <span class="nt">&quot;start&quot;</span><span class="p">:</span> <span class="s2">&quot;11.00&quot;</span><span class="p">,</span> <span class="nt">&quot;stop&quot;</span><span class="p">:</span> <span class="s2">&quot;14.35&quot;</span><span class="p">}</span> <span class="p">]</span> <span class="p">}</span> <span class="p">]</span> <span class="p">}</span> <span class="p">]</span> <span class="p">}</span> </pre></div> <blockquote> <p><strong>Note:</strong><br /> It's kept short for brevity: the actual document contained many more items in each of the nested lists (so multiple groups, categories, and points), but this snippet covers the overall structure.</p> </blockquote> <h2 id="analysis">Analysis <a href="#analysis" rel="bookmark" class="permalink">¶</a></h2> <p>This is an incredibly common task I'm sure any programmer with a sufficiently long career has encountered in one shape or form.</p> <p>The simple, <em>ad hoc</em>, solution to the problem above is:</p> <div class="codehilite"><pre><span class="k">def</span> <span class="nf">sort_points</span><span class="p">(</span><span class="n">d</span><span class="p">):</span> <span class="k">for</span> <span class="n">group</span> <span class="ow">in</span> <span class="n">d</span><span class="p">[</span><span class="s">&#39;res&#39;</span><span class="p">]:</span> <span class="k">for</span> <span class="n">cat</span> <span class="ow">in</span> <span class="n">group</span><span class="p">[</span><span class="s">&#39;catlist&#39;</span><span class="p">]:</span> <span class="n">cat</span><span class="p">[</span><span class="s">&#39;points&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">cat</span><span class="p">[</span><span class="s">&#39;points&#39;</span><span class="p">],</span> <span class="n">reverse</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">p</span><span class="p">:</span> <span class="n">p</span><span class="p">[</span><span class="s">&#39;stop&#39;</span><span class="p">])</span> </pre></div> <p>Some downsides in arbitrary order:</p> <ul> <li><strong>Not reusable.</strong> This function can only deal with dicts of the exact same structure. It's required to know the key names and the type of data living at each nesting level. Any other dict will make it choke;</li> <li><strong>Brittle.</strong> The algorithm itself needs to be changed when the document gets nested in another document, or when its structure should change. Nest it in another dictionary, and you need an extra <code>for</code> loop in there. Pass it just a category, and you need to take out a <code>for</code> loop;</li> <li><strong>Lacks abstraction.</strong> The algorithm mixes traversing the dict with modifying it—these should be two separate things.</li> <li><strong>Changes the dict in-place.</strong> There's no need to rely on using mutable data structures here. It should work for dicts you cannot change, too.</li> </ul> <h2 id="solution">Solution <a href="#solution" rel="bookmark" class="permalink">¶</a></h2> <p>How do we solve this more elegantly?</p> <p>The data itself isn't interesting in the slightest. This is a problem of structure only. Let's try to break out the pieces that are <em>specific</em> for this problem and see if we can factor out a generic piece, taking the specific parts as arguments.</p> <p>The three key tasks we need to perform:</p> <ol> <li>traverse the entire structure recursively;</li> <li>determine if we've arrived at a given designated path;</li> <li>change the nested structure at that location (using given function).</li> </ol> <p>Note that these steps already show our function params. We need a way of specifying the "path" to drill down into, and specify what transformation to apply to those targeted elements.</p> <hr /> <h4 id="traversal">Traversal <a href="#traversal" rel="bookmark" class="permalink">¶</a></h4> <p>First and foremost, we need a way of traversing arbitrarily nested structures. Given that this is only JSON data (so limited to strings, numbers, lists and dicts), we can start with a recursive function that will walk the structure and produce a new output which will essentially be a deep copy of the input:</p> <div class="codehilite"><pre><span class="k">def</span> <span class="nf">traverse</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="nb">dict</span><span class="p">):</span> <span class="k">return</span> <span class="p">{</span><span class="n">k</span><span class="p">:</span> <span class="n">traverse</span><span class="p">(</span><span class="n">v</span><span class="p">)</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">obj</span><span class="o">.</span><span class="n">items</span><span class="p">()}</span> <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="nb">list</span><span class="p">):</span> <span class="k">return</span> <span class="p">[</span><span class="n">traverse</span><span class="p">(</span><span class="n">elem</span><span class="p">)</span> <span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">obj</span><span class="p">]</span> <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="n">obj</span> <span class="c"># no container, just values (str, int, float)</span> </pre></div> <p>Here are some examples:</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">traverse</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="go">3</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">traverse</span><span class="p">(</span><span class="s">&#39;ohai&#39;</span><span class="p">)</span> <span class="go">&#39;ohai&#39;</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">traverse</span><span class="p">([</span><span class="s">&#39;ohai&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s">&#39;name&#39;</span><span class="p">:</span> <span class="s">&#39;Vincent&#39;</span><span class="p">,</span> <span class="s">&#39;age&#39;</span><span class="p">:</span> <span class="mi">32</span><span class="p">}])</span> <span class="go">[&#39;ohai&#39;, {&#39;name&#39;: &#39;Vincent&#39;, &#39;age&#39;: 32}]</span> </pre></div> <hr /> <h4 id="path-matching">Path Matching <a href="#path-matching" rel="bookmark" class="permalink">¶</a></h4> <p>To specify the target path into the structure, we need to come up with a syntax that can express those, a mini-language. Here's an example:</p> <div class="codehilite"><pre>&#39;res[].catlist[].points&#39; </pre></div> <p>This notation clearly specifies the steps to take to drill down into the structure to arrive at any nested element. Note that each step is explicit: it's either a step into a dict key (the string), or into a list (the empty list). This convenient string notation is of course just sugar for the following:</p> <div class="codehilite"><pre><span class="p">[</span><span class="s">&#39;res&#39;</span><span class="p">,</span> <span class="p">[],</span> <span class="s">&#39;catlist&#39;</span><span class="p">,</span> <span class="p">[],</span> <span class="s">&#39;points&#39;</span><span class="p">]</span> </pre></div> <p>How can we use this structure? Let's take the <code>traverse()</code> function and change it to keep a record of the paths it's traversing along as it traverses:</p> <div class="codehilite"><pre><span class="k">def</span> <span class="nf">traverse</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">path</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span> <span class="k">if</span> <span class="n">path</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span> <span class="n">path</span> <span class="o">=</span> <span class="p">[]</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="nb">dict</span><span class="p">):</span> <span class="k">return</span> <span class="p">{</span><span class="n">k</span><span class="p">:</span> <span class="n">traverse</span><span class="p">(</span><span class="n">v</span><span class="p">,</span> <span class="n">path</span> <span class="o">+</span> <span class="p">[</span><span class="n">k</span><span class="p">])</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">obj</span><span class="o">.</span><span class="n">items</span><span class="p">()}</span> <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="nb">list</span><span class="p">):</span> <span class="k">return</span> <span class="p">[</span><span class="n">traverse</span><span class="p">(</span><span class="n">elem</span><span class="p">,</span> <span class="n">path</span> <span class="o">+</span> <span class="p">[[]])</span> <span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">obj</span><span class="p">]</span> <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="n">obj</span> </pre></div> <p>But we're not doing anyting with the <code>path</code> we're tracking this way yet.</p> <hr /> <h4 id="applying-an-action">Applying an Action <a href="#applying-an-action" rel="bookmark" class="permalink">¶</a></h4> <p>Now we need to use that path and in the interesting case perform an action. One way is to add that to the <code>traverse()</code> function, but it would do more than just traversing that way. Let's update the traverse function with a callback argument that will get called for every node in the structure (every leaf, dict entry, or list item). This would fully decouple traversing the structure from modifying it.</p> <div class="codehilite"><pre><span class="k">def</span> <span class="nf">traverse</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">path</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">callback</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span> <span class="k">if</span> <span class="n">path</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span> <span class="n">path</span> <span class="o">=</span> <span class="p">[]</span> <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="nb">dict</span><span class="p">):</span> <span class="n">value</span> <span class="o">=</span> <span class="p">{</span><span class="n">k</span><span class="p">:</span> <span class="n">traverse</span><span class="p">(</span><span class="n">v</span><span class="p">,</span> <span class="n">path</span> <span class="o">+</span> <span class="p">[</span><span class="n">k</span><span class="p">],</span> <span class="n">callback</span><span class="p">)</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">obj</span><span class="o">.</span><span class="n">items</span><span class="p">()}</span> <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="nb">list</span><span class="p">):</span> <span class="n">value</span> <span class="o">=</span> <span class="p">[</span><span class="n">traverse</span><span class="p">(</span><span class="n">elem</span><span class="p">,</span> <span class="n">path</span> <span class="o">+</span> <span class="p">[[]],</span> <span class="n">callback</span><span class="p">)</span> <span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">obj</span><span class="p">]</span> <span class="k">else</span><span class="p">:</span> <span class="n">value</span> <span class="o">=</span> <span class="n">obj</span> <span class="k">if</span> <span class="n">callback</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span> <span class="c"># if a callback is provided, call it to get the new value</span> <span class="k">return</span> <span class="n">value</span> <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="n">callback</span><span class="p">(</span><span class="n">path</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span> </pre></div> <p>Now the <code>traverse()</code> function is really generic and can be used to replace any node in the structure. We can now implement our <code>traverse_modify()</code> function that will look for a specific node, and update it. In this example, the <code>transformer()</code> function is our callback that will be invoked on every node in the structure. If the current path matches the target path, it will perform the action.</p> <div class="codehilite"><pre><span class="k">def</span> <span class="nf">traverse_modify</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">target_path</span><span class="p">,</span> <span class="n">action</span><span class="p">):</span> <span class="n">target_path</span> <span class="o">=</span> <span class="n">to_path</span><span class="p">(</span><span class="n">target_path</span><span class="p">)</span> <span class="c"># converts &#39;foo.bar&#39; to [&#39;foo&#39;, &#39;bar&#39;]</span> <span class="c"># This will get called for every path/value in the structure</span> <span class="k">def</span> <span class="nf">transformer</span><span class="p">(</span><span class="n">path</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span> <span class="k">if</span> <span class="n">path</span> <span class="o">==</span> <span class="n">target_path</span><span class="p">:</span> <span class="k">return</span> <span class="n">action</span><span class="p">(</span><span class="n">value</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="n">value</span> <span class="k">return</span> <span class="n">traverse</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">callback</span><span class="o">=</span><span class="n">transformer</span><span class="p">)</span> </pre></div> <h2 id="back-to-the-problem">Back to the Problem <a href="#back-to-the-problem" rel="bookmark" class="permalink">¶</a></h2> <p>There we have it: a generic, reusable function that abstracted out each individual interaction: traversal, path matching, and action. To solve our original problem with it, now simply call:</p> <div class="codehilite"><pre><span class="kn">from</span> <span class="nn">operator</span> <span class="kn">import</span> <span class="n">itemgetter</span> <span class="k">def</span> <span class="nf">sort_points</span><span class="p">(</span><span class="n">points</span><span class="p">):</span> <span class="sd">&quot;&quot;&quot;Will sort a list of points.&quot;&quot;&quot;</span> <span class="k">return</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">points</span><span class="p">,</span> <span class="n">reverse</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">itemgetter</span><span class="p">(</span><span class="s">&#39;stop&#39;</span><span class="p">))</span> <span class="n">traverse_modify</span><span class="p">(</span><span class="n">doc</span><span class="p">,</span> <span class="s">&#39;res[].catlist[].points&#39;</span><span class="p">,</span> <span class="n">sort_points</span><span class="p">)</span> </pre></div> <p>Here's the gist to the <a href="https://gist.github.com/nvie/f304caf3b4f1ca4c3884">complete solution</a>.</p> <h2 id="go-wild">Go Wild <a href="#go-wild" rel="bookmark" class="permalink">¶</a></h2> <p>This blog post was meant to provide some insight into a typical software engineering approach to problem solving. Breaking down a problem into pieces, and abstracting out the essence is perhaps the most joyful thing to do as an engineer.</p> <p>The constructed <code>traverse_modify()</code> function could be written in many different ways if you would like to give it more power. Examples are supporting the following path specs:</p> <div class="codehilite"><pre>qux[].(foo|bar)[] # match both foo or bar results[0..4] # only apply action to first 4 results foo.bar.* # match any key value foo.bar.**.qux # match 0 or more levels of keys ... </pre></div> <p>Another extension would be to allow it to take multiple target-path/action combinations and apply them all in a single traversal.</p> <p>All of that is left as an exercise to the reader though, to keep this post clear and concise.</p> <h2 id="summary">Summary <a href="#summary" rel="bookmark" class="permalink">¶</a></h2> <p>The fantastic thing is that, picking a good abstraction for the <code>traverse()</code> function opens a door to an entire world of possibilities to modify arbitrary Python object structures. In the end, you get more than you initially set out for.</p> <p>If you build something cool based on this however, please let me know :)</p> Yesterday, a friend asked me how I would solve a certain problem he was facing. He did have a working solution, but felt like he could make it more generally applicable. Not shying away at a good challenge, I decided to take it and see how I would solve it. In this blog post you can read about my solution. 2014-10-03T00:00:00+00:00 http://nvie.com/posts/use-more-iterators/ Use More Iterators 2014-10-01T00:00:00+00:00 <p>One of my top favorite features of the Python programming language is generators. They are so useful, yet I don't encounter them often enough when reading open source code. In this post I hope to outline their simplest use case and hope to encourage any readers to use them more often.</p> <p>This post assumes you know what a container and an iterator is. I've explained these concepts in a <a href="/posts/iterators-vs-generators/">previous blog post</a>.</p> <h2 id="why">Why? <a href="#why" rel="bookmark" class="permalink">¶</a></h2> <p>Why are iterators a good idea? Code using iterators can avoid intermediate variables, lead to shorter code, run lazily, consume less memory, run faster, are composable, and are more beautiful. In short: they are more elegant.</p> <blockquote> <p>"The moment you've made something iterable, you've done something magic with your code. As soon as something's iterable, you can feed it to <code>list()</code>, <code>set()</code>, <code>sorted()</code>, <code>min()</code>, <code>max()</code>, <code>heapify()</code>, <code>sum()</code>, ‥. Many of the tools in Python consume iterators."</p> <p style="text-align: right">— Raymond Hettinger (<a href="https://www.youtube.com/watch?v=OSGv2VnC0go#t=825">source</a>)</p> </blockquote> <p>Recently, Clojure added transducers to the language, which is a concept pretty similar to generators in Python. (I highly recommend watching <a href="https://www.youtube.com/watch?v=6mTbuzafcII">Rich Hickey's talk</a> at Strange Loop 2014 where he introduces them.)</p> <p>In the video, he talks about "pouring" one collection into another, which I think is a verb that very intuitively describes the nature of iterators in relationship to datastructures. I'm going to write about this idea in more detail in a future blog post. <!-- TODO: link to future post --></p> <h2 id="example">Example <a href="#example" rel="bookmark" class="permalink">¶</a></h2> <p>Here's an example of a pattern commonly seen:</p> <div class="codehilite"><pre><span class="k">def</span> <span class="nf">get_lines</span><span class="p">(</span><span class="n">f</span><span class="p">):</span> <span class="n">result</span> <span class="o">=</span> <span class="p">[]</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">line</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s">&#39;#&#39;</span><span class="p">):</span> <span class="n">result</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">line</span><span class="p">)</span> <span class="k">return</span> <span class="n">result</span> <span class="n">lines</span> <span class="o">=</span> <span class="n">get_lines</span><span class="p">(</span><span class="n">f</span><span class="p">)</span> </pre></div> <p>Now look at the equivalent thing as a generator:</p> <div class="codehilite"><pre><span class="k">def</span> <span class="nf">get_lines</span><span class="p">(</span><span class="n">f</span><span class="p">):</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">line</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s">&#39;#&#39;</span><span class="p">):</span> <span class="k">yield</span> <span class="n">line</span> <span class="n">lines</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">get_lines</span><span class="p">(</span><span class="n">f</span><span class="p">))</span> </pre></div> <!-- By the way, this generator is simple enough that you could even write it as a generator expression: # Equivalent to the generator function get_lines = (line for line in f if not line.startswith('#')) --> <h2 id="the-benefits">The Benefits <a href="#the-benefits" rel="bookmark" class="permalink">¶</a></h2> <p>Not much of a difference at first sight, but the benefits are pretty substantial.</p> <ul> <li><strong>No bookkeeping.</strong> You don't have to create an empty list, append to it, and return it. One more variable gone;</li> <li><strong>Hardly consumes memory.</strong> No matter how large the input file is, the iterator version does not need to buffer the entire file in memory;</li> <li><strong>Works with infinite streams.</strong> The iterator version still works if <code>f</code> is an infinite stream (i.e. stdin);</li> <li><strong>Faster results.</strong> Results can be consumed immediately, not after the entire file is read;</li> <li><strong>Speed.</strong> The iterator version runs faster than building a list the naive way;</li> <li><strong>Composability.</strong> The caller gets to decide how it wants to use the result.</li> </ul> <p>The last bullet is by far the most important one. Let's dig in.</p> <h2 id="composability">Composability <a href="#composability" rel="bookmark" class="permalink">¶</a></h2> <p>Composability is key here. Iterators are incredibly composable. In the example, a list is built explicitly. What if the caller actually needs a set? In practice, many people will either create a second, set-based version of the same function, or simply wrap the call in a <code>set()</code>. Surely that works, but it is a waste of resources. Imagine the large file again. First a list is built from the entire file. Then it's passed to <code>set()</code> to build another collection in memory. Then the original list is garbage collected.</p> <p>With generators, the function just "emits" a stream of objects. The caller gets to decide <em>into</em> what collection those objects gets poured.</p> <p class="centered"><img alt="" src="/img/generator-explained-by-your-finest-TAP@2x.png" width="545" /></p> <p>Want a set instead of a list?</p> <div class="codehilite"><pre><span class="n">uniq_lines</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="n">get_lines</span><span class="p">(</span><span class="n">f</span><span class="p">))</span> </pre></div> <p>Want just the longest line from the file? The file will be read entirely, but at most two lines are kept in memory at all times:</p> <div class="codehilite"><pre><span class="n">longest_line</span> <span class="o">=</span> <span class="nb">max</span><span class="p">(</span><span class="n">get_lines</span><span class="p">(</span><span class="n">f</span><span class="p">),</span> <span class="n">key</span><span class="o">=</span><span class="nb">len</span><span class="p">)</span> </pre></div> <p>Want just the first 10 lines from the file? No more than 10 lines will be read from the file, no matter how large it is:</p> <div class="codehilite"><pre><span class="n">head</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">islice</span><span class="p">(</span><span class="n">get_lines</span><span class="p">(</span><span class="n">f</span><span class="p">),</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">10</span><span class="p">))</span> </pre></div> <h2 id="loop-like-a-native">Loop Like a Native <a href="#loop-like-a-native" rel="bookmark" class="permalink">¶</a></h2> <p><strong>Update:</strong> At PyCon 2013, Ned Batchelder gave a great talk that perfectly reflects what I tried to explain in this blog post. You can watch it here, I highly recommend it:</p> <iframe width="560" height="420" style="display: block; margin-left: auto; margin-right: auto;" src="//www.youtube.com/embed/EnSu9hHGq5o" frameborder="0" allowfullscreen> </iframe> <h2 id="summary">Summary <a href="#summary" rel="bookmark" class="permalink">¶</a></h2> <p>Don't collect data in a result variable. You can almost always avoid them. You gain readability, speed, a smaller memory footprint, and composability in return.</p> One of my top favorite features of the Python programming language is generators. They are so useful, yet I don't encounter them often enough when reading open source code. In this post I hope to outline their simplest use case and hope to encourage any readers to use them more often. 2014-09-29T00:00:00+00:00 http://nvie.com/posts/iterators-vs-generators/ Iterables vs. Iterators vs. Generators 2014-09-25T00:00:00+00:00 <p>Occasionally I've run into situations of confusion on the exact differences between the following related concepts in Python:</p> <ul> <li>a container</li> <li>an iterable</li> <li>an iterator</li> <li>a generator</li> <li>a generator expression</li> <li>a {list, set, dict} comprehension</li> </ul> <p>I'm writing this post as a pocket reference for later.</p> <p class="centered"><img alt="" src="/img/relationships.png" width="636" /></p> <h2 id="containers">Containers <a href="#containers" rel="bookmark" class="permalink">¶</a></h2> <p>Containers are data structures holding elements, and that support membership tests. They are data structures that live in memory, and typically hold all their values in memory, too. In Python, some well known examples are:</p> <ul> <li><strong>list</strong>, deque, …</li> <li><strong>set</strong>, frozensets, …</li> <li><strong>dict</strong>, defaultdict, OrderedDict, Counter, …</li> <li><strong>tuple</strong>, namedtuple, …</li> <li><strong>str</strong></li> </ul> <p>Containers are easy to grasp, because you can think of them as real life containers: a box, a cubboard, a house, a ship, etc.</p> <p>Technically, an object is a container when it can be asked whether it <u>contains</u> a certain element. You can perform such membership tests on lists, sets, or tuples alike:</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">assert</span> <span class="mi">1</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span> <span class="c"># lists</span> <span class="gp">&gt;&gt;&gt; </span><span class="k">assert</span> <span class="mi">4</span> <span class="ow">not</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span> <span class="gp">&gt;&gt;&gt; </span><span class="k">assert</span> <span class="mi">1</span> <span class="ow">in</span> <span class="p">{</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">}</span> <span class="c"># sets</span> <span class="gp">&gt;&gt;&gt; </span><span class="k">assert</span> <span class="mi">4</span> <span class="ow">not</span> <span class="ow">in</span> <span class="p">{</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">}</span> <span class="gp">&gt;&gt;&gt; </span><span class="k">assert</span> <span class="mi">1</span> <span class="ow">in</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="c"># tuples</span> <span class="gp">&gt;&gt;&gt; </span><span class="k">assert</span> <span class="mi">4</span> <span class="ow">not</span> <span class="ow">in</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> </pre></div> <p>Dict membership will check the keys:</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="mi">1</span><span class="p">:</span> <span class="s">&#39;foo&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">:</span> <span class="s">&#39;bar&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">:</span> <span class="s">&#39;qux&#39;</span><span class="p">}</span> <span class="gp">&gt;&gt;&gt; </span><span class="k">assert</span> <span class="mi">1</span> <span class="ow">in</span> <span class="n">d</span> <span class="gp">&gt;&gt;&gt; </span><span class="k">assert</span> <span class="mi">4</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">d</span> <span class="gp">&gt;&gt;&gt; </span><span class="k">assert</span> <span class="s">&#39;foo&#39;</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">d</span> <span class="c"># &#39;foo&#39; is not a _key_ in the dict</span> </pre></div> <p>Finally you can ask a string if it "contains" a substring:</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s">&#39;foobar&#39;</span> <span class="gp">&gt;&gt;&gt; </span><span class="k">assert</span> <span class="s">&#39;b&#39;</span> <span class="ow">in</span> <span class="n">s</span> <span class="gp">&gt;&gt;&gt; </span><span class="k">assert</span> <span class="s">&#39;x&#39;</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">s</span> <span class="gp">&gt;&gt;&gt; </span><span class="k">assert</span> <span class="s">&#39;foo&#39;</span> <span class="ow">in</span> <span class="n">s</span> <span class="c"># a string &quot;contains&quot; all its substrings</span> </pre></div> <p>The last example is a bit strange, but it shows how the container interface renders the object opaque. A string does not literally store copies of all of its substrings in memory, but you can certainly use it that way.</p> <blockquote> <p><strong>NOTE:</strong><br /> Even though most containers provide a way to produce every element they contain, that ability does not make them a container but an iterable (we'll get there in a minute).</p> <p>Not all containers are necessarily iterable. An example of this is a <a href="http://en.wikipedia.org/wiki/Bloom_filter">Bloom filter</a>. Probabilistic data structures like this can be asked whether they contain a <em>certain</em> element, but they are unable to return their individual elements.</p> </blockquote> <h2 id="iterables">Iterables <a href="#iterables" rel="bookmark" class="permalink">¶</a></h2> <p>As said, most containers are also iterable. But many more things are iterable as well. Examples are open files, open sockets, etc. Where containers are typically finite, an iterable may just as well represent an infinite source of data.</p> <p>An <strong>iterable</strong> is any object, not necessarily a data structure, that can return an <strong>iterator</strong> (with the purpose of returning all of its elements). That sounds a bit awkward, but there is an important difference between an iterable and an iterator. Take a look at this example:</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">z</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">y</span><span class="p">)</span> <span class="go">1</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">y</span><span class="p">)</span> <span class="go">2</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">z</span><span class="p">)</span> <span class="go">1</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="go">&lt;class &#39;list&#39;&gt;</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">y</span><span class="p">)</span> <span class="go">&lt;class &#39;list_iterator&#39;&gt;</span> </pre></div> <p>Here, <code>x</code> is the iter<u>able</u>, while <code>y</code> and <code>z</code> are two individual instances of an iterat<u>or</u>, producing values from the iterable <code>x</code>. Both <code>y</code> and <code>z</code> hold state, as you can see from the example. In this example, <code>x</code> is a data structure (a list), but that is not a requirement.</p> <blockquote> <p><strong>NOTE:</strong><br /> Often, for pragmatic reasons, iterable classes will implement both <code>__iter__()</code> and <code>__next__()</code> in the same class, and have <code>__iter__()</code> return <code>self</code>, which makes the class both an iterable and its own iterator. It is perfectly fine to return a different object as the iterator, though.</p> </blockquote> <p>Finally, when you write:</p> <div class="codehilite"><pre><span class="n">x</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span> <span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">x</span><span class="p">:</span> <span class="o">...</span> </pre></div> <p>This is what actually happens:</p> <p class="centered"><img alt="" src="/img/iterable-vs-iterator.png" width="584" /></p> <p>When you disassemble this Python code, you can see the explicit call to <code>GET_ITER</code>, which is essentially like invoking <code>iter(x)</code>. The <code>FOR_ITER</code> is an instruction that will do the equivalent of calling <code>next()</code> repeatedly to get every element, but this does not show from the byte code instructions because it's optimized for speed in the interpreter.</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">dis</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">dis</span><span class="o">.</span><span class="n">dis</span><span class="p">(</span><span class="s">&#39;for _ in x: pass&#39;</span><span class="p">)</span> <span class="go"> 1 0 SETUP_LOOP 14 (to 17)</span> <span class="go"> 3 LOAD_NAME 0 (x)</span> <span class="go"> 6 GET_ITER</span> <span class="go"> &gt;&gt; 7 FOR_ITER 6 (to 16)</span> <span class="go"> 10 STORE_NAME 1 (_)</span> <span class="go"> 13 JUMP_ABSOLUTE 7</span> <span class="go"> &gt;&gt; 16 POP_BLOCK</span> <span class="go"> &gt;&gt; 17 LOAD_CONST 0 (None)</span> <span class="go"> 20 RETURN_VALUE</span> </pre></div> <h2 id="iterators">Iterators <a href="#iterators" rel="bookmark" class="permalink">¶</a></h2> <p>So what is an <strong>iterator</strong> then? It's a stateful helper object that will produce the next value when you call <code>next()</code> on it. Any object that has a <code>__next__()</code> method is therefore an iterator. How it produces a value is irrelevant.</p> <p>So an iterator is a value factory. Each time you ask it for "the next" value, it knows how to compute it because it holds internal state.</p> <p>There are countless examples of iterators. All of the <code>itertools</code> functions return iterators. Some produce infinite sequences:</p> <div class="codehilite"><pre><span class="o">&gt;&gt;&gt;</span> <span class="kn">from</span> <span class="nn">itertools</span> <span class="kn">import</span> <span class="n">count</span> <span class="o">&gt;&gt;&gt;</span> <span class="n">counter</span> <span class="o">=</span> <span class="n">count</span><span class="p">(</span><span class="n">start</span><span class="o">=</span><span class="mi">13</span><span class="p">)</span> <span class="o">&gt;&gt;&gt;</span> <span class="nb">next</span><span class="p">(</span><span class="n">counter</span><span class="p">)</span> <span class="mi">13</span> <span class="o">&gt;&gt;&gt;</span> <span class="nb">next</span><span class="p">(</span><span class="n">counter</span><span class="p">)</span> <span class="mi">14</span> </pre></div> <p>Some produce infinite sequences from finite sequences:</p> <div class="codehilite"><pre><span class="o">&gt;&gt;&gt;</span> <span class="kn">from</span> <span class="nn">itertools</span> <span class="kn">import</span> <span class="n">cycle</span> <span class="o">&gt;&gt;&gt;</span> <span class="n">colors</span> <span class="o">=</span> <span class="n">cycle</span><span class="p">([</span><span class="s">&#39;red&#39;</span><span class="p">,</span> <span class="s">&#39;white&#39;</span><span class="p">,</span> <span class="s">&#39;blue&#39;</span><span class="p">])</span> <span class="o">&gt;&gt;&gt;</span> <span class="nb">next</span><span class="p">(</span><span class="n">colors</span><span class="p">)</span> <span class="s">&#39;red&#39;</span> <span class="o">&gt;&gt;&gt;</span> <span class="nb">next</span><span class="p">(</span><span class="n">colors</span><span class="p">)</span> <span class="s">&#39;white&#39;</span> <span class="o">&gt;&gt;&gt;</span> <span class="nb">next</span><span class="p">(</span><span class="n">colors</span><span class="p">)</span> <span class="s">&#39;blue&#39;</span> <span class="o">&gt;&gt;&gt;</span> <span class="nb">next</span><span class="p">(</span><span class="n">colors</span><span class="p">)</span> <span class="s">&#39;red&#39;</span> </pre></div> <p>Some produce finite sequences from infinite sequences:</p> <div class="codehilite"><pre><span class="o">&gt;&gt;&gt;</span> <span class="kn">from</span> <span class="nn">itertools</span> <span class="kn">import</span> <span class="n">islice</span> <span class="o">&gt;&gt;&gt;</span> <span class="n">colors</span> <span class="o">=</span> <span class="n">cycle</span><span class="p">([</span><span class="s">&#39;red&#39;</span><span class="p">,</span> <span class="s">&#39;white&#39;</span><span class="p">,</span> <span class="s">&#39;blue&#39;</span><span class="p">])</span> <span class="c"># infinite</span> <span class="o">&gt;&gt;&gt;</span> <span class="n">limited</span> <span class="o">=</span> <span class="n">islice</span><span class="p">(</span><span class="n">colors</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="c"># finite</span> <span class="o">&gt;&gt;&gt;</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">limited</span><span class="p">:</span> <span class="c"># so safe to use for-loop on</span> <span class="o">...</span> <span class="k">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="n">red</span> <span class="n">white</span> <span class="n">blue</span> <span class="n">red</span> </pre></div> <p>To get a better sense of the internals of an iterator, let's build an iterator producing the Fibonacci numbers:</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">fib</span><span class="p">:</span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">prev</span> <span class="o">=</span> <span class="mi">0</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">curr</span> <span class="o">=</span> <span class="mi">1</span> <span class="gp">... </span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="k">return</span> <span class="bp">self</span> <span class="gp">... </span> <span class="gp">... </span> <span class="k">def</span> <span class="nf">__next__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="gp">... </span> <span class="n">value</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">curr</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">curr</span> <span class="o">+=</span> <span class="bp">self</span><span class="o">.</span><span class="n">prev</span> <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">prev</span> <span class="o">=</span> <span class="n">value</span> <span class="gp">... </span> <span class="k">return</span> <span class="n">value</span> <span class="gp">...</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">fib</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">islice</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">10</span><span class="p">))</span> <span class="go">[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]</span> </pre></div> <p>Note that this class is both an iterable (because it sports an <code>__iter__()</code> method), and its own iterator (because it has a <code>__next__()</code> method).</p> <p>The state inside this iterator is fully kept inside the <code>prev</code> and <code>curr</code> instance variables, and are used for subsequent calls to the iterator. Every call to <code>next()</code> does two important things:</p> <ol> <li>Modify its state for the next <code>next()</code> call;</li> <li>Produce the result for the current call.</li> </ol> <blockquote> <p><strong>Central idea: a lazy factory</strong><br /> From the outside, the iterator is like a lazy factory that is idle until you ask it for a value, which is when it starts to buzz and produce a single value, after which it turns idle again.</p> </blockquote> <h2 id="generators">Generators <a href="#generators" rel="bookmark" class="permalink">¶</a></h2> <p>Finally, we've arrived at our destination! The generators are my absolute favorite Python language feature. A generator is a special kind of iterator—the elegant kind.</p> <p>A generator allows you to write iterators much like the Fibonacci sequence iterator example above, but in an elegant succinct syntax that avoids writing classes with <code>__iter__()</code> and <code>__next__()</code> methods.</p> <p>Let's be explicit:</p> <ul> <li>Any generator also is an iterator (not vice versa!);</li> <li>Any generator, therefore, is a factory that lazily produces values.</li> </ul> <p>Here is the same Fibonacci sequence factory, but written as a generator:</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">fib</span><span class="p">():</span> <span class="gp">... </span> <span class="n">prev</span><span class="p">,</span> <span class="n">curr</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span> <span class="gp">... </span> <span class="k">while</span> <span class="bp">True</span><span class="p">:</span> <span class="gp">... </span> <span class="k">yield</span> <span class="n">curr</span> <span class="gp">... </span> <span class="n">prev</span><span class="p">,</span> <span class="n">curr</span> <span class="o">=</span> <span class="n">curr</span><span class="p">,</span> <span class="n">prev</span> <span class="o">+</span> <span class="n">curr</span> <span class="gp">...</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">fib</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">islice</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">10</span><span class="p">))</span> <span class="go">[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]</span> </pre></div> <p>Wow, isn't that elegant? Notice the magic keyword that's responsible for the beauty:</p> <blockquote> <p><code>yield</code></p> </blockquote> <p>Let's break down what happened here: first of all, take note that <code>fib</code> is defined as a normal Python function, nothing special. Notice, however, that there's no <code>return</code> keyword inside the function body. The return value of the function will be a generator (read: an iterator, a factory, a stateful helper object).</p> <p>Now when <code>f = fib()</code> is called, the generator (the factory) is instantiated and returned. No code will be executed at this point: the generator starts in an idle state initially. To be explicit: the line <code>prev, curr = 0, 1</code> is not executed yet.</p> <p>Then, this generator instance is wrapped in an <code>islice()</code>. This is itself also an iterator, so idle initially. Nothing happens, still.</p> <p>Then, this iterator is wrapped in a <code>list()</code>, which will consume all of its arguments and build a list from it. To do so, it will start calling <code>next()</code> on the <code>islice()</code> instance, which in turn will start calling <code>next()</code> on our <code>f</code> instance.</p> <p>But one step at a time. On the first invocation, the code will finally run a bit: <code>prev, curr = 0, 1</code> gets executed, the <code>while True</code> loop is entered, and then it encounters the <code>yield curr</code> statement. It will produce the value that's currently in the <code>curr</code> variable and become idle again.</p> <p>This value is passed to the <code>islice()</code> wrapper, which will produce it (because it's not past the 10th value yet), and list can add the value <code>1</code> to the list now.</p> <p>Then, it asks <code>islice()</code> for the next value, which will ask <code>f</code> for the next value, which will "unpause" <code>f</code> from its previous state, resuming with the statement <code>prev, curr = curr, prev + curr</code>. Then it re-enters the next iteration of the <code>while</code> loop, and hits the <code>yield curr</code> statement, returning the next value of <code>curr</code>.</p> <p>This happens until the output list is 10 elements long and when <code>list()</code> asks <code>islice()</code> for the 11th value, <code>islice()</code> will raise a <code>StopIteration</code> exception, indicating that the end has been reached, and list will return the result: a list of 10 items, containing the first 10 Fibonacci numbers. Notice that the generator doesn't receive the 11th <code>next()</code> call. In fact, it will not be used again, and will be garbage collected later.</p> <h3 id="types-of-generators">Types of Generators <a href="#types-of-generators" rel="bookmark" class="permalink">¶</a></h3> <p>There are two types of generators in Python: generator <strong>functions</strong> and generator <strong>expressions</strong>. A generator function is any function in which the keyword <code>yield</code> appears in its body. We just saw an example of that. The appearance of the keyword <code>yield</code> is enough to make the function a generator function.</p> <p>The other type of generators are the generator equivalent of a list comprehension. Its syntax is really elegant for a limited use case.</p> <p>Suppose you use this syntax to build a list of sqaures:</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">numbers</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">]</span> <span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">x</span> <span class="o">*</span> <span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">numbers</span><span class="p">]</span> <span class="go">[1, 4, 9, 16, 25, 36]</span> </pre></div> <p>You could do the same thing with a set comprehension:</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="p">{</span><span class="n">x</span> <span class="o">*</span> <span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">numbers</span><span class="p">}</span> <span class="go">{1, 4, 36, 9, 16, 25}</span> </pre></div> <p>Or a dict comprehension:</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="p">{</span><span class="n">x</span><span class="p">:</span> <span class="n">x</span> <span class="o">*</span> <span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">numbers</span><span class="p">}</span> <span class="go">{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}</span> </pre></div> <p>But you can also use a generator expression (note: this is <em>not</em> a tuple comprehension):</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">lazy_squares</span> <span class="o">=</span> <span class="p">(</span><span class="n">x</span> <span class="o">*</span> <span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">numbers</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">lazy_squares</span> <span class="go">&lt;generator object &lt;genexpr&gt; at 0x10d1f5510&gt;</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">next</span><span class="p">(</span><span class="n">lazy_squares</span><span class="p">)</span> <span class="go">1</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">lazy_squares</span><span class="p">)</span> <span class="go">[4, 9, 16, 25, 36]</span> </pre></div> <p>Note that, because we read the first value from <code>lazy_sqaures</code> with <code>next()</code>, it's state is now at the "second" item, so when we consume it entirely by calling <code>list()</code>, that will only return the partial list of sqaures. (This is just to show the lazy behaviour.) This is as much a generator (and thus, an iterator) as the other examples above.</p> <h2 id="summary">Summary <a href="#summary" rel="bookmark" class="permalink">¶</a></h2> <p>Generators are an incredible powerful programming construct. They allow you to write streaming code with fewer intermediate variables and data structures. Besides that, they are more memory and CPU efficient. Finally, they tend to require fewer lines of code, too.</p> <p>Tip to get started with generators: find places in your code where you do the following:</p> <div class="codehilite"><pre><span class="k">def</span> <span class="nf">something</span><span class="p">():</span> <span class="n">result</span> <span class="o">=</span> <span class="p">[]</span> <span class="k">for</span> <span class="o">...</span> <span class="ow">in</span> <span class="o">...</span><span class="p">:</span> <span class="n">result</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="k">return</span> <span class="n">result</span> </pre></div> <p>And replace it by:</p> <div class="codehilite"><pre><span class="k">def</span> <span class="nf">iter_something</span><span class="p">():</span> <span class="k">for</span> <span class="o">...</span> <span class="ow">in</span> <span class="o">...</span><span class="p">:</span> <span class="k">yield</span> <span class="n">x</span> <span class="c"># def something(): # Only if you really need a list structure</span> <span class="c"># return list(iter_something())</span> </pre></div> Occasionally I've run into situations of confusion on the exact differences between the following related concepts in Python: 2014-09-25T00:00:00+00:00 http://nvie.com/posts/better-package-management/ Better Package Management 2013-05-08T00:00:00+00:00 <p>You are managing your Python packages using <code>pip</code> and <code>requirements.txt</code> spec files already. Maybe, you are even <a href="/posts/pin-your-packages/">pinning them</a> too—that’s awesome. But how do you keep your environments clean and fresh?</p> <p>Here’s what I think can be improved to the state of package management in Python.</p> <h2 id="virtue-1-declare-only-your-top-level-dependencies">Virtue 1: Declare only your top-level dependencies <a href="#virtue-1-declare-only-your-top-level-dependencies" rel="bookmark" class="permalink">¶</a></h2> <p>Often, your project will only need a limited set of what I’ll call <em>top-level</em> package dependencies. A typical example is that you’ll depend on Djang or Flask. But just putting those names in an <code>requirements.txt</code> file is inherently dangerous and will bite you at some point. If you don’t see why, <a href="/posts/pin-your-packages/">read this post</a> first.</p> <p>So now you’re pinning them. If your app needs Flask, this will typically be in your <code>requirements.txt</code> file:</p> <div class="codehilite"><pre>Flask==0.9 Jinja2==2.6 Werkzeug==0.8.3 </pre></div> <p>Jinja2 and Werkzeug are in there, because Flask needs them. And since you don’t want fate to decide which versions of Jinja2 and Werkzeug you’ll get when deploying, you’re wisely pinning them.</p> <p>The problem with this is that over time your <code>requirements.txt</code> file will accumulate all kinds of dependencies, and in reality, it’s not unusual that you’ll lose sight of which packages are still used, and which have become stale.</p> <p>The following file is the result of depending on Flask and legit.</p> <div class="codehilite"><pre>async==0.6.1 clint==0.3.1 Flask==0.9 gitdb==0.5.4 GitPython==0.3.2.RC1 Jinja2==2.6 legit==0.1.1 smmap==0.8.2 Werkzeug==0.8.3 </pre></div> <p>Looking at this, I’d have no clue what <code>smmap</code> is, and why it’s needed in there.</p> <p>Wouldn’t it be awesome to actually have a way of expressing only your top-level dependencies in a file called <code>requirements.in</code>, like this?</p> <div class="codehilite"><pre>Flask&gt;=0.9 # we use 0.9 features legit # any version will do for us </pre></div> <p>And “compiling” that to an actual <code>requirements.txt</code>:</p> <div class="codehilite"><pre>async==0.6.1 # required by legit==0.1.1 clint==0.3.1 # required by legit==0.1.1 Flask==0.9 gitdb==0.5.4 # required by legit==0.1.1 GitPython==0.3.2.RC1 # required by legit==0.1.1 Jinja2==2.6 # required by Flask==0.9 legit==0.1.1 smmap==0.8.2 # required by legit==0.1.1 Werkzeug==0.8.3 # required by Flask==0.9 </pre></div> <p>This tool exists, and is called <code>pip-compile</code>. Check it out on the <a href="https://github.com/nvie/pip-tools/tree/future"><code>future</code> branch</a> of pip-tools. (<strong>UPDATE</strong> This is now the master branch, available since 1.0.) I wrote this together with <a href="http://twitter.com/brutasse">Bruno Renié</a> over the last few months.</p> <p>Let’s elaborate on this a bit. The <code>.in</code> file provides the file format that you’d <em>actually</em> would want to use and maintain as a developer, while the result of compilation is the file that you want to use to build deterministic (and thus predictable) envs.</p> <p>Note that there’s a fundamental difference here between “compiling” these <code>.in</code> files and compiling a file of source code: the result of the compilation itself isn’t deterministic. This means that compiling your requirements may lead to a different <code>requirements.txt</code> file depending on the moment you run it—because in the meantime some packages might have gotten updates in PyPI.</p> <p>The point is to freeze the specs. Exactly why you were pinning your dependencies already.</p> <p>As a consequence, you should put both files under version control. This plays well with PAAS providers like Heroku as well. The <code>.in</code> file is only used for your own maintenance convenience, while the <code>.txt</code> file is actually used to install to your env. The difference is, it’s now generated for you.</p> <blockquote> <p><strong>A Quick Note on Complex Dependencies</strong><br /> We’ve created <code>pip-compile</code> to be smart with respect to resolving complex dependency trees. For example, Flask 0.9 depends on <code>Jinja2&gt;=2.4</code>. If another package, say Foo, declared <code>Jinja2&lt;2.6</code>, you’ll end up having <code>Jinja2==2.5</code> in your compiled requirements. It can figure this out. (Obviously, conflicts can occur, in which case compilation will fail.)</p> </blockquote> <h2 id="virtue-2-have-your-envs-reflect-your-specs">Virtue 2: Have your envs reflect your specs <a href="#virtue-2-have-your-envs-reflect-your-specs" rel="bookmark" class="permalink">¶</a></h2> <p>The next step, then, would be to rebuild your actual virtualenvs by having them reflect <em>exactly</em> what’s in your (compiled) spec file. Let’s replay the example above.</p> <p>Recall that we have this in our <code>requirements.in</code> file:</p> <div class="codehilite"><pre>Flask&gt;=0.9 legit </pre></div> <p>Then we run <code>pip-compile</code>, and get:</p> <div class="codehilite"><pre>async==0.6.1 # required by legit==0.1.1 clint==0.3.1 # required by legit==0.1.1 Flask==0.9 gitdb==0.5.4 # required by legit==0.1.1 GitPython==0.3.2.RC1 # required by legit==0.1.1 Jinja2==2.6 # required by Flask==0.9 legit==0.1.1 smmap==0.8.2 # required by legit==0.1.1 Werkzeug==0.8.3 # required by Flask==0.9 </pre></div> <p>Now, to actually install that into our environment, we typically run:</p> <div class="codehilite"><pre><span class="gp">$</span> pip install -r requirements.txt </pre></div> <p>But frankly, this isn’t enough. To actually reliably mimic the spec file, the env might need to uninstall some packages as well. This can actually be very important. Suppose you have a package that’s already installed in your env, say <code>requests</code>. Your code is using it, but you forgot to add it to <code>requirements.txt</code>. That way, running <code>pip install -r requirements.txt</code> will work fine, but deploying this code will break due to an ImportError.</p> <p>Meet <code>pip-sync</code>. This tool will install all required packages into your env, but will additionally <em>uninstall</em> everything else in there. Combined with <code>pip-compile</code>, this makes for package management nirvana. Say you don’t need <code>legit</code> anymore, and want to remove it as a project dependency.</p> <p>First, remove that top-level dependency from the <code>.in</code> file:</p> <div class="codehilite"><pre>Flask # legit # comment out, or remove </pre></div> <p>Then run <code>pip-compile</code> to update the compiled spec file:</p> <div class="codehilite"><pre>Flask==0.9 Jinja2==2.6 # required by Flask==0.9 Werkzeug==0.8.3 # required by Flask==0.9 </pre></div> <p>The unused dependencies are removed automatically. Now we need to sync that back to our actual env:</p> <div class="codehilite"><pre><span class="gp">$</span> pip-sync <span class="go">Uninstalling package async</span> <span class="go">Uninstalling package clint</span> <span class="go">Uninstalling package gitdb</span> <span class="go">Uninstalling package GitPython</span> <span class="go">Uninstalling package smmap</span> </pre></div> <p>This will now uninstall legit and all it’s dependencies from the virtualenv (unless some other package would depend on them still). Your virtualenv is crisp and clean.</p> <p>I would propose PAAS providers to adopt the use of <code>pip-sync</code> over <code>pip install -r requirements.txt</code>, as environments are automatically cleaned up that way.</p> <h2 id="project-context-and-roadmap">Project context and roadmap <a href="#project-context-and-roadmap" rel="bookmark" class="permalink">¶</a></h2> <p>As said, over the last few months, <a href="http://twitter.com/brutasse">Bruno Renié</a> and myself have been working on a better version of the <code>pip-tools</code> project—one that would let us do exactly the above. We’ve not been very public about it, but you might have noticed the <a href="https://github.com/nvie/pip-tools/tree/future"><code>future</code> branch</a>. Basically, this would replace the existing <code>pip-dump</code> command by something inherently more manageable.</p> <p>I do solicit feedback on all this, so feel free to get in touch.</p> You are managing your Python packages using `pip` and `requirements.txt` spec files already. Maybe, you are even [pinning them](/posts/pin-your-packages/) too—that’s awesome. But how do you keep your environments clean and fresh? 2013-05-08T00:00:00+00:00 http://nvie.com/posts/alexander-klopping-in-silicon-valley/ Alexander Klöpping in Silicon Valley 2013-05-07T00:00:00+00:00 <p>Over the last three weeks, the Dutch broadcaster <a href="http://www.vara.nl">VARA</a> has been airing three special episodes of <a href="http://dewerelddraaitdoor.vara.nl/DWDD-University.2772.0.html">DWDD University</a>: a documentary <a href="http://www.twitter.com/AlexanderNL">Alexander Klöpping</a> made about Silicon Valley.</p> <p>The episodes can be freely watched <a href="http://dewerelddraaitdoor.vara.nl/Alexander-Kloepping.3006.0.html">online</a>. I transcribed the episodes in an attempt to make it available to the whole world.</p> <p><strong>Copyright notice.</strong> I only link to the original footage from the VARA here, in order to overlay the subs. I didn’t steal any of the content. The subs are provided by myself.</p> <h2 id="episode-10-the-rise">Episode 1.0: The Rise <a href="#episode-10-the-rise" rel="bookmark" class="permalink">¶</a></h2> <p class="embedded-video"> <script type="text/javascript" src="http://s3.amazonaws.com/s3.www.universalsubtitles.org/embed.js"> ( {"base_state": {"language": "en"}, "video_url": "http://content10c4b.omroep.nl/7cee71f8f10b50e90595f3dddcdad400/517bdc4f/vara/tv/dewerelddraaitdoor/20130426-dwdd-univklopping1-hq.mp4"} ) </script> </p> <p>Footage is courtesy of VARA.</p> <h2 id="episode-20-the-valley-now">Episode 2.0: The Valley Now <a href="#episode-20-the-valley-now" rel="bookmark" class="permalink">¶</a></h2> <p class="embedded-video"> <script type="text/javascript" src="http://s3.amazonaws.com/s3.www.universalsubtitles.org/embed.js"> ( {"base_state": {"language": "en"}, "video_url": "http://download.omroep.nl/vara/tv/dewerelddraaitdoor/20130503-dwdd-univklopping2-hq.mp4"} ) </script> </p> <p>Footage is courtesy of VARA.</p> <h2 id="episode-30-the-future">Episode 3.0: The Future <a href="#episode-30-the-future" rel="bookmark" class="permalink">¶</a></h2> <p>By the time you read this, episode 3.0 hasn’t aired yet. But I’ll update this post once it’s available, too.</p> Over the last three weeks, the Dutch broadcaster [VARA](http://www.vara.nl) has been airing three special episodes of [DWDD University](http://dewerelddraaitdoor.vara.nl/DWDD-University.2772.0.html): a documentary [Alexander Klöpping](http://www.twitter.com/AlexanderNL) made about Silicon Valley. 2013-05-07T00:00:00+00:00 http://nvie.com/posts/pin-your-packages/ Pin Your Packages 2013-05-08T00:00:00+00:00 <p>In building your Python application and its dependencies for production, you want to make sure that your builds are predictable and deterministic. Therefore, always pin your dependencies.</p> <p><strong>Update:</strong> A newer blog post about the future of pip-tools is available too: <a href="/posts/better-package-management/">Better Package Management</a>.</p> <h2 id="pin-explicitly">Pin Explicitly <a href="#pin-explicitly" rel="bookmark" class="permalink">¶</a></h2> <p>Don’t ever use these styles in <code>requirements.txt</code>:</p> <ul> <li><code>lxml</code></li> <li><code>lxml&gt;=2.2.0</code></li> <li><code>lxml&gt;=2.2.0,&lt;2.3.0</code></li> </ul> <p>Instead, pin them:</p> <ul> <li><code>lxml==2.3.4</code></li> </ul> <p>If you don’t, you can never know what you’ll get when you run <code>pip install</code>. Even if you rebuild the env every time, you still can’t predict it. The outcome relies on a) what’s currently installed, and b) what’s the current version on PyPI.</p> <p>Eventually, all of your environments, and those of your team members, will run out of sync. Worse even, this cannot be fixed by rerunning <code>pip install</code>. It’s just waiting for bad things to happen in production.</p> <p>The only way of making your builds deterministic, is if you pin <em>every</em> single package dependency (even the dependency’s dependencies).</p> <blockquote> <p><strong>WARNING:</strong> Don’t pin by default when you’re building libraries! Only use pinning for end products.</p> </blockquote> <p>The biggest complaint from folks regarding explicit pinning is that you won’t benefit from updates that way. Well, yes, you won’t. But think of it. It’s impossible to distinguish between a new release that fixes bugs, or one that introduced them. You are leaving it up to coincidence. There is only one way to retake control: <em>pin every dependency</em>.</p> <h2 id="check-for-updates-automatically">Check for Updates Automatically <a href="#check-for-updates-automatically" rel="bookmark" class="permalink">¶</a></h2> <p>So: we want to pin packages, but don’t want to let them become outdated. The solution: use a tool that can check for updates. This is exactly what I built <a href="https://github.com/nvie/pip-tools">pip-tools</a> for.</p> <p>pip-tools is the collective name for two tools: <code>pip-review</code> + <code>pip-dump</code></p> <p class="centered"><img alt="" src="/img/pip-tools.png" /></p> <h2 id="pip-review">pip-review <a href="#pip-review" rel="bookmark" class="permalink">¶</a></h2> <p>It will check for available updates of all packages currently installed in your environment, and report about them when available:</p> <div class="codehilite"><pre><span class="gp">$</span> pip-review <span class="go">requests==0.14.0 available (you have 0.13.2)</span> <span class="go">redis==2.6.2 available (you have 2.4.9)</span> <span class="go">rq==0.3.2 available (you have 0.3.0)</span> </pre></div> <p>You can also install them automatically:</p> <div class="codehilite"><pre><span class="gp">$</span> pip-review --auto <span class="go">... </span> </pre></div> <p>or interactively decide whether you want to install each package:</p> <div class="codehilite"><pre><span class="gp">$</span> pip-review --interactive <span class="go">requests==0.14.0 available (you have 0.13.2)</span> <span class="go">Upgrade now? [Y]es, [N]o, [A]ll, [Q]uit y</span> <span class="go">... </span> <span class="go">redis==2.6.2 available (you have 2.4.9)</span> <span class="go">Upgrade now? [Y]es, [N]o, [A]ll, [Q]uit n</span> <span class="go">rq==0.3.2 available (you have 0.3.0)</span> <span class="go">Upgrade now? [Y]es, [N]o, [A]ll, [Q]uit y</span> <span class="go">... </span> </pre></div> <p>It’s advisable to pick a fixed schedule to run <code>pip-review</code>. For example, every monday during a weekly standup meeting with your engineering team. Make it a point on the agenda. You discuss <code>pip-review</code>’s output, inspect changelogs, or just blindly upgrade them. The important part is that you do it explicitly. You have the chance to run with the upgraded versions for a while in a development environment, before pushing those versions to production.</p> <h2 id="pip-dump">pip-dump <a href="#pip-dump" rel="bookmark" class="permalink">¶</a></h2> <p>Whereas <code>pip-review</code> solves the problem of how to check for updates of pinned packages, <code>pip-dump</code> focuses on the problem of how to dump those definitions into requirements files, managed under version control.</p> <p>Typically, in Python apps, you include a <code>requirements.txt</code> file in the root of your project directory, and you run <code>pip freeze &gt; requirements.txt</code> periodically. While this works for simple projects, this doesn’t scale. Some packages are installed for development, or personal, purposes only and you don’t want to include those in <code>requirements.txt</code>, going to production, or visible to your other team members.</p> <p><code>pip-dump</code> provides a smarter way to dump requirements. It understands the convention of separating requirements into multiple files, following the naming convention:</p> <ul> <li><code>requirements.txt</code> is the main (and default) requirements file;</li> <li><code>dev-requirements.txt</code>, or <code>test-requirements.txt</code>, or actually, <code>*requirements.txt</code>, are secundary dependencies.</li> </ul> <p>When you have a <code>requirements.txt</code> and <code>dev-requirements.txt</code> file in your project, with the following content:</p> <div class="codehilite"><pre># requirements.txt Flask==0.9 # dev-requirements.txt ipython </pre></div> <p>Then simply running <code>pip-dump</code> will result in the following output:</p> <div class="codehilite"><pre># requirements.txt Flask==0.9 Jinja2==2.6 Werkzeug==0.8.3 # dev-requirements.txt ipython==0.13 </pre></div> <p>It keeps the files sorted for tidiness, and to reduce the chance of merge conflicts in version control.</p> <p>You can even put packages in an optional file called <code>.pipignore</code>. This is useful if you want to keep some packages installed in your local environment, but don’t want to have them reflected in your requirements files.</p> <h2 id="contributing">Contributing <a href="#contributing" rel="bookmark" class="permalink">¶</a></h2> <p><code>pip-tools</code> 0.x is relied on by many already on a daily/weekly basis. It’s worth noting that we’re working on <a href="/posts/better-package-management/">Better Package Management</a> too, which will be the future of <code>pip-tools</code>. If you want to contribute, please shout out.</p> In building your Python application and its dependencies for production, you want to make sure that your builds are predictable and deterministic. Therefore, always pin your dependencies. 2012-09-26T00:00:00+00:00 http://nvie.com/posts/open-sourcing-is-the-ultimate-isolation/ Open Sourcing: the Ultimate Isolation 2012-09-09T00:00:00+00:00 <p>Reflecting on how I build software lately, I noticed a pattern. I tend to write libraries in absolute isolation, <em>as if they were open sourced</em> and the world is watching along.</p> <p>Let me try to explain why this works for me.</p> <h2 id="where-theory-fails">Where Theory Fails <a href="#where-theory-fails" rel="bookmark" class="permalink">¶</a></h2> <blockquote> <p><em>“The difference between theory and practice is that, in theory, there is none.”</em></p> </blockquote> <p>We have all been schooled to isolate units of software into reusable components. Software engineering literature refers to this as separation of concerns since decades. It reduces the big problem into smaller non-overlapping problems.</p> <p>We obviously try doing so, by putting related logic into modules, libraries and whatnot. Yet, in practice, so many real world projects fail at their attempts and end up evolving into something unnecessarily complicated.</p> <p>The main problem with this is that it becomes increasingly hard to comprehend and reason about your software, not to mention the “increased fun” maintaining it.</p> <p>Why is it so hard to actually achieve this in practice? Separating concerns apparently is easier said than done.</p> <h2 id="how-things-evolve">How Things Evolve <a href="#how-things-evolve" rel="bookmark" class="permalink">¶</a></h2> <p>The need for a new library often arises when solving a larger problem top-down. In the quest of solving a larger problem, you need to create a smaller component first that is required to get to a fully working solution. This is what most of our work as engineers is about—while solving a larger problem, we run into bumps along the road. When we do, we stop, fix the bump, and continue on our journey to solving the large problem.</p> <p>In our rush to arrive at our end destination, we want to fix any bumps as quickly as possible. For many good reasons, mostly. We might have a deadline, or we are afraid to get lost in details and lose focus on the bigger problem we were actually solving.</p> <p>In short, we tend to see those bumps as unsolicited chores that are blocking us and we want to spend as little time as possible at overcoming them. From a quality perspective, however, this may not be the best route to take. So the least you can do is create that <em>Technical Debt</em> ticket, feel less guilty, and move on :)</p> <p>I’ve never seen a project work any more glorious than this.</p> <h2 id="step-back-breathe-accept-open-source">Step Back, Breathe, Accept, Open Source <a href="#step-back-breathe-accept-open-source" rel="bookmark" class="permalink">¶</a></h2> <p>Running into these bumps sucks. You’re frustrated that you’re held up and are continuously thinking: dammit, I don’t want to deal with this now. The reality often is that you don’t have a choice.</p> <p>Instead, step back a few steps, take a deep breath, and accept that you’ll have to spend more time on this problem than budgeted. This enables the mental rest to make a good engineering decision without too much frustration emotion involved.</p> <p><strong>What I like to do at this moment, is to start a new open source project.</strong></p> <p>Not necessarily a public one, but I do set it up like it is and <em>actually consider</em> it to be, or eventually become, open. I start out with a README decribing the problem and the API I’d like it to have. And in the case of Python, I also create a <code>setup.py</code> so integrating this into the original project is only a <code>pip install</code> away.</p> <p>Then, just start implementing it.</p> <p>Let me try to highlight the benefits this approach provides.</p> <h2 id="youre-more-likely-to-do-it-right">You’re More Likely To Do It Right <a href="#youre-more-likely-to-do-it-right" rel="bookmark" class="permalink">¶</a></h2> <p>The pressure you get from pretending (or knowing) that many others will read your code, pushes you to do it right. I’d ask myself continuously: would this be an API that I’d show off to the outside world and be proud of? Could I truly explain this API in a README so that people would understand? If not, I don’t implement it like that and push harder.</p> <p>Many eyeballs make you feel more responsible. Writing stuff in private for yourself, doesn’t.</p> <h2 id="no-cheating">No Cheating <a href="#no-cheating" rel="bookmark" class="permalink">¶</a></h2> <p>A big difference between starting an actual new project, or developing it as one-of-many internal libraries, is that it’s impossible to rely on other parts of the end product. For example, that convenient project-specific helper function you already wrote is easily included in a module, but not so much in another project.</p> <p>In an open source project, you simply cannot cheat on yourself this way and you’re forced to come up with a better solution. This might feel inconvenient at first, but remember that it’s easy to write complex software and it takes more care and dedication to write simpler software.</p> <p>As a way of visualising this approach: compare programming to electrical engineering for a minute. Say you have to create a circuit board of some sort.</p> <p class="centered"><img alt="" src="/img/circuit-board.jpg" /></p> <p>The chip on this board is analogous to an open source software project. Its internals are nicely abstracted away, the pins of the chip form its API, it’s probably well-tested, well-documented and can be reused immediately. It is physically impossible to connect to any of the internals of it—which is exactly the point of abstraction.</p> <p>Looking at the circuit board, everything about this falls into place pretty obviously.</p> <p>As programmers, we often fool ourselves that we’re <em>isolating</em> logic into modules/libraries, while in fact we’re merely <em>organising</em> it. Modules will oftentimes still contain project-specific dependencies. (As a good litmus test, move that module to an empty directory and use it. If it breaks, it wasn’t truly isolated.)</p> <p>The curse with programming is that it’s so easy to create these dependencies. They are only one <code>import</code> statement away. Developers live in a world where that temptation continuously lurks.</p> <p>But by isolating code into a stand-alone project, you can remove this temptation wholly, thereby reducing ways of cheating on yourself.</p> <h2 id="simplicity-pays">Simplicity Pays <a href="#simplicity-pays" rel="bookmark" class="permalink">¶</a></h2> <p>Another big benefit of truly isolating your libraries this way, is that you are forced to think about its API. It’s the <em>only</em> way of interacting with the library after all. Doing this, you’ll naturally feel the urge to simplify. Complex APIs lead to complicated documentation and complex tests. The opposite applies, too, fortunately, and you’ll naturally be inclined to simplify.</p> <p>A concrete example of this: When you are hacking in a web environment, you most likely have “the request” or “the DB connection” at your disposal any time. When you put your library in a module, it’s easy for these to become implicit dependencies of your library. Your library may pretty well work outside of a request context, however, and in fact, the only thing you actually need from the request could be a <code>User</code> instance. When you build your library as a separate project, these decisions fall into place effortlessly. In the end, this makes your library more decoupled, more generic, and overall cleaner. And as such, simpler.</p> <p>True Isolation™ is the ultimate catalyst of simplicity.</p> <h2 id="sharing-can-pay-off-too">Sharing Can Pay Off, Too <a href="#sharing-can-pay-off-too" rel="bookmark" class="permalink">¶</a></h2> <p>Even if you’re only using this technique privately to produce better software for yourself, this pays off already in a technical sense.</p> <p>But open sourcing can also pay off in non-technical ways. When it fits your company’s strategy, you now have the choice to actually publish your project at any time, since it’s been written for the public from the beginning. If it solves a common problem, others may like it and take interest in following it or even contributing to it. This may open up a whole new world of users providing feedback and improvements through code or documentation contributions.</p> <p>Your company may come across as an interesting place to work for to talented people. Your open source project can be your company’s banner. We’ve seen this with companies like <a href="http://joyent.com/">Joyent</a> (of Node.js fame), <a href="http://www.10gen.com/">10gen</a> (of MongoDB fame) and <a href="http://www.opscode.com/">Opscode</a> (of Chef fame), just to name a few. Open sourcing has been an important marketing value to these companies and they have attracted many talented folks through their high-quality work.</p> <p>Just always remember that <em>simpler</em> projects have a much lower barrier for contributors, so these are more likely to receive patches. Which by itself is another good reason to simplify your libraries :)</p> <h2 id="how-i-built-rq">How I Built RQ <a href="#how-i-built-rq" rel="bookmark" class="permalink">¶</a></h2> <p>Many of the things I created recently, I created this way. Back a few months ago, I needed a super-simple solution to put work in the background. I was working on a startup idea, which I was creating a proof of concept for. It was a small Flask web app, and I used <a href="http://flask.pocoo.org/snippets/73/">this snippet</a> initially to offload work to the background. It did the work fine, but I soon needed it to do more, so I kept tweaking it until it was no longer a snippet, but a library. Although it was nicely organised in a directory, it was still tailored to the specific product I was creating.</p> <p>This is where I decided to step back and started building that library like an open source project, which became <a href="http://python-rq.org/">RQ</a>, of course. After using it privately for about four months, its API kept changing quite a bit, but its use became more general over time. I started reusing it for other projects I was working on, until I considered it stable enough. I believed it could be of help to other Python engineers, so I <a href="/posts/introducing-rq/">decided to open source RQ</a> in March.</p> <p>Eventually I dropped the original startup idea, but I still have RQ. Had I not open sourced it, it would now be buried with the rest of that project’s code.</p> <p>Open sourcing pays off. Even if you do it in private.</p> Some thoughts on how I like to write libraries as "open source" projects. 2012-09-09T00:00:00+00:00 http://nvie.com/posts/introducing-rq/ Introducing RQ 2012-03-28T00:00:00+00:00 <p>Today, I’m open sourcing a project that I’ve been working for the last few months. It is a Python library to put work in the background, that you’d typically use in a web context. It is designed to be simple to set up and use, and be of help in almost any modern Python web stack.</p> <p class="centered"><img alt="" src="/img/rq-site@2x.png" style="max-width: 637px" /></p> <h2 id="existing-solutions">Existing solutions <a href="#existing-solutions" rel="bookmark" class="permalink">¶</a></h2> <p>Of course, there already exist a few solutions to this problem. <a href="http://celeryproject.org/">Celery</a> (by the excellent <a href="http://twitter.com/#!/asksol">@asksol</a>) is by far the most popular Python framework for working with asynchronous tasks. It is agnostic about the underlying queueing implementation, which is quite powerful, but also poses a learning curve and requires a fair amount of setup.</p> <p>Don’t get me wrong—I think Celery is a great library. In fact, <a href="https://github.com/ask/celery/commits/master?author=nvie">I’ve contributed</a> to Celery myself in the past. My experiences are, however, that as your Python web project grows, there comes this moment where you want to start offloading small pieces of code into the background. Setting up Celery for these cases is a substantial effort that isn’t done swiftly and might be holding you back.</p> <p>I wanted something simpler. Something that you’d use in <em>all</em> of your Python web projects, not only the big and serious ones.</p> <h2 id="redis-as-a-broker">Redis as a broker <a href="#redis-as-a-broker" rel="bookmark" class="permalink">¶</a></h2> <p>In many modern web stacks, chances are that you’re already using <a href="http://redis.io/">Redis</a> (by <a href="http://twitter.com/#!/antirez">@antirez</a>). Besides being a kick-ass key value store, Redis also provides semantics to build a perfect queue implementation. The commands <a href="http://redis.io/commands/rpush"><code>RPUSH</code></a>, <a href="http://redis.io/commands/lpop"><code>LPOP</code></a> and <a href="http://redis.io/commands/blpop"><code>BLPOP</code></a> are all it takes.</p> <p>Inspired by <a href="https://github.com/resque/resque">Resque</a> (by <a href="https://github.com/defunkt/resque">defunkt</a>) and the simplicity of <a href="http://flask.pocoo.org/snippets/73/">this Flask snippet</a> (by <a href="http://twitter.com/#!/mitsuhiko">@mitsuhiko</a>), I’ve challenged myself to imagine just how hard a job queue library really should be.</p> <h2 id="introducing-rq">Introducing RQ <a href="#introducing-rq" rel="bookmark" class="permalink">¶</a></h2> <p>I wanted a solution that was lightweight, easy to adopt, and easy to grasp. So I devised a simple queueing library for Python, and dubbed it <a href="https://github.com/nvie/rq">RQ</a>. In a nutshell, you define a job like you would any normal Python function.</p> <div class="codehilite"><pre><span class="k">def</span> <span class="nf">myfunc</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span> <span class="k">return</span> <span class="n">x</span> <span class="o">*</span> <span class="n">y</span> </pre></div> <p>Now, with RQ, it is ridiculously easy to put it in the background like this:</p> <div class="codehilite"><pre><span class="kn">from</span> <span class="nn">rq</span> <span class="kn">import</span> <span class="n">use_connection</span><span class="p">,</span> <span class="n">Queue</span> <span class="c"># Connect to Redis</span> <span class="n">use_connection</span><span class="p">()</span> <span class="c"># Offload the &quot;myfunc&quot; invocation</span> <span class="n">q</span> <span class="o">=</span> <span class="n">Queue</span><span class="p">()</span> <span class="n">q</span><span class="o">.</span><span class="n">enqueue</span><span class="p">(</span><span class="n">myfunc</span><span class="p">,</span> <span class="mi">318</span><span class="p">,</span> <span class="mi">62</span><span class="p">)</span> </pre></div> <p>This puts the equivalent of <code>myfunc(318, 62)</code> on the <code>default</code> queue. Now, in another shell, run a separate worker process to perform the actual work:</p> <div class="codehilite"><pre><span class="gp">$</span> rqworker <span class="go">12:46:56:</span> <span class="go">12:46:56: *** Listening on default...</span> <span class="go">12:47:35: default: mymodule.myfunc(318, 62) (38d9c157-e997-40e2-8d20-574a97ec5a99</span> <span class="go">12:47:35: Job OK, result = 19716</span> <span class="go">12:47:35:</span> <span class="go">12:47:35: *** Listening on default...</span> <span class="go">...</span> </pre></div> <p>To poll for the asynchronous result in the web backend, you can use:</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">r</span> <span class="o">=</span> <span class="n">q</span><span class="o">.</span><span class="n">enqueue</span><span class="p">(</span><span class="n">myfunc</span><span class="p">,</span> <span class="mi">318</span><span class="p">,</span> <span class="mi">62</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">r</span><span class="o">.</span><span class="n">return_value</span> <span class="go">None</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">r</span><span class="o">.</span><span class="n">return_value</span> <span class="go">19716</span> </pre></div> <p>Although I must admit that polling for job results through the <code>return_value</code> isn’t quite useful and probably won’t be a pattern that you’d use in your day-to-day work. (I would certainly recommend against doing that, at least.)</p> <p>There’s extensive documentation available at: <a href="http://nvie.github.com/rq">http://nvie.github.com/rq</a>.</p> <h2 id="near-zero-configuration">Near-zero configuration <a href="#near-zero-configuration" rel="bookmark" class="permalink">¶</a></h2> <p>RQ was designed to be as easy as possible to start using it immediately inside your Python web projects. You only need to pass it a Redis connection to use, because I didn’t want it to create new connections implicitly.</p> <p>To use the default Redis connection (to <code>localhost:6379</code>), you only have to do this:</p> <div class="codehilite"><pre><span class="kn">from</span> <span class="nn">rq</span> <span class="kn">import</span> <span class="n">use_connection</span> <span class="n">use_connection</span><span class="p">()</span> </pre></div> <p>You can reuse an existing Redis connection that you are already using and pass it into RQ’s <code>use_connection</code> function:</p> <div class="codehilite"><pre><span class="kn">import</span> <span class="nn">redis</span> <span class="kn">from</span> <span class="nn">rq</span> <span class="kn">import</span> <span class="n">use_connection</span> <span class="n">my_connection</span> <span class="o">=</span> <span class="n">redis</span><span class="o">.</span><span class="n">Redis</span><span class="p">(</span><span class="n">hostname</span><span class="o">=</span><span class="s">&#39;example.com&#39;</span><span class="p">,</span> <span class="n">port</span><span class="o">=</span><span class="mi">6379</span><span class="p">)</span> <span class="n">use_connection</span><span class="p">(</span><span class="n">my_connection</span><span class="p">)</span> </pre></div> <p>There are more advanced ways of connection management available however, <a href="http://nvie.github.com/rq/docs/connections/">so please pick your favorite</a>. You can safely mix your Redis data with RQ, as RQ prefixes all of its keys with <code>rq:</code>.</p> <h2 id="building-your-own-queueing-system">Building your own queueing system <a href="#building-your-own-queueing-system" rel="bookmark" class="permalink">¶</a></h2> <p>RQ offers functionality to put work on queues. It provides FIFO-semantics per queue, but how many queues you create is up to you. For the simplest cases, simply using the <code>default</code> queue suffices already.</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">q</span> <span class="o">=</span> <span class="n">Queue</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="o">.</span><span class="n">name</span> <span class="go">&#39;default&#39;</span> </pre></div> <p>But you can name your queues however you want:</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">lo</span> <span class="o">=</span> <span class="n">Queue</span><span class="p">(</span><span class="s">&#39;low&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">hi</span> <span class="o">=</span> <span class="n">Queue</span><span class="p">(</span><span class="s">&#39;high&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">lo</span><span class="o">.</span><span class="n">enqueue</span><span class="p">(</span><span class="n">myfunc</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">lo</span><span class="o">.</span><span class="n">enqueue</span><span class="p">(</span><span class="n">myfunc</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">hi</span><span class="o">.</span><span class="n">enqueue</span><span class="p">(</span><span class="n">myfunc</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">lo</span><span class="o">.</span><span class="n">count</span> <span class="go">2</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">hi</span><span class="o">.</span><span class="n">count</span> <span class="go">1</span> </pre></div> <p>Both queues are equally important to RQ. None of these has higher priority as far as RQ is concerned. But when you start a worker, you are defining queue priority by the order of the arguments:</p> <div class="codehilite"><pre><span class="gp">$</span> rqworker high low <span class="go">12:47:35:</span> <span class="go">12:47:35: *** Listening on high, low...</span> <span class="go">12:47:35: high: mymodule.myfunc(6, 7) (cc183988-a507-4623-b31a-f0338031b613)</span> <span class="go">12:47:35: Job OK, result = 42</span> <span class="go">12:47:35:</span> <span class="go">12:47:35: *** Listening on high, low...</span> <span class="go">12:47:35: low: mymodule.myfunc(2, 3) (95fe658e-b23d-4aff-9307-a55a0ee55650)</span> <span class="go">12:47:36: Job OK, result = 6</span> <span class="go">12:47:36:</span> <span class="go">12:47:36: *** Listening on high, low...</span> <span class="go">12:47:36: low: mymodule.myfunc(4, 5) (bfb89229-3ce4-463c-abf8-f19c2808cb7c)</span> <span class="go">12:47:36: Job OK, result = 20</span> <span class="go">...</span> </pre></div> <p>First, all work on the <code>high</code> queue is done (with FIFO semantics), then <code>low</code> is emptied. If meanwhile work is enqueued on <code>high</code>, that work takes precedence over the <code>low</code> queue again after the currently running job is finished.</p> <p>No rocket science here, just what you’d expect.</p> <h2 id="insight-over-performance">Insight over performance <a href="#insight-over-performance" rel="bookmark" class="permalink">¶</a></h2> <p>One of the things I missed most in other queueing systems is to have a decent view of what’s going on in the system. For example:</p> <ul> <li>What queues exist?</li> <li>How many messages are on each queue?</li> <li>What workers are listening on what queues?</li> <li>Who’s idle or busy?</li> <li>What actual messages are on the queue?</li> </ul> <p>RQ provides an answer to all of these questions (except for the last one, currently), via the <code>rqinfo</code> tool.</p> <div class="codehilite"><pre><span class="gp">$</span> rqinfo <span class="go">high |██████████████████████████ 20</span> <span class="go">low |██████████████ 12</span> <span class="go">default |█████████ 8</span> <span class="go">3 queues, 45 jobs total</span> <span class="go">Bricktop.19233 idle: low</span> <span class="go">Bricktop.19232 idle: high, default, low</span> <span class="go">Bricktop.18349 idle: default</span> <span class="go">3 workers, 3 queues</span> </pre></div> <p>Showing only a subset of queues (including empty ones):</p> <div class="codehilite"><pre><span class="gp">$</span> rqinfo high archive <span class="go">high |██████████████████████████ 20</span> <span class="go">archive | 0</span> <span class="go">2 queues, 20 jobs total</span> <span class="go">Bricktop.19232 idle: high</span> <span class="go">1 workers, 2 queues</span> </pre></div> <p>If you want to parse the output of this script, you can specify the <code>--raw</code> flag to disable the fancy drawing. Example:</p> <div class="codehilite"><pre><span class="gp">$</span> rqinfo --raw <span class="go">queue high 20</span> <span class="go">queue low 12</span> <span class="go">queue default 8</span> <span class="go">worker Bricktop.19233 idle low</span> <span class="go">worker Bricktop.19232 idle high,default,low</span> <span class="go">worker Bricktop.18349 idle default</span> </pre></div> <p>You can also sort the same data by queue:</p> <div class="codehilite"><pre><span class="gp">$</span> rqinfo --by-queue <span class="go">high |██████████████████████████ 20</span> <span class="go">low |██████████████ 12</span> <span class="go">default |█████████ 8</span> <span class="go">3 queues, 45 jobs total</span> <span class="go">high: Bricktop.19232 (idle)</span> <span class="go">low: Bricktop.19233 (idle), Bricktop.19232 (idle)</span> <span class="go">default: Bricktop.18349 (idle), Bricktop.19232 (idle)</span> <span class="go">3 workers, 4 queues</span> </pre></div> <p>By default, these monitoring commands autorefresh every 2.5 seconds, but you can change the refresh interval if you want to. See the <a href="http://nvie.github.com/rq/docs/monitoring/">monitoring docs</a> for more info.</p> <h2 id="limitations">Limitations <a href="#limitations" rel="bookmark" class="permalink">¶</a></h2> <p>RQ does not try to solve all of your queueing needs. But its codebase is relatively small and certainly not overly complex. Nonetheless, I think it will be helpful for all of the most basic queueing needs that you’ll encounter during Python web development.</p> <p>Of course, with all this also come some limitations:</p> <ul> <li>It’s Python-only</li> <li>It’s Redis-only</li> <li>The workers are Unix-only</li> </ul> <h2 id="please-give-feedback">Please, give feedback <a href="#please-give-feedback" rel="bookmark" class="permalink">¶</a></h2> <p>I’m using RQ for two and a half web projects I’ve worked on during the last few months, and I am currently at the point where I’m satisfied enough to open the curtains to the world. So you’re invited to play with it. I’m very curious to hear your thoughts about this.</p> <p>If you’d like to contribute, please go <a href="https://github.com/nvie/rq">fork me on GitHub</a>.</p> Today, I'm open sourcing a project that I've been working for the last few months. It is a Python library to put work in the background, that you'd typically use in a web context. It is designed to be simple to set up and use, and be of help in almost any modern Python web stack. 2012-03-28T00:00:00+00:00 http://nvie.com/posts/vim-flake8-flake8-for-vim/ vim-flake8: Flake8 for Vim 2012-02-14T00:00:00+00:00 <p>Just a quick post to let you know that I discarded my <code>vim-pep8</code> and <code>vim-pyflakes</code> Vim plugins yesterday in favor of <a href="https://github.com/nvie/vim-flake8">vim-flake8</a>.</p> <p>As you may know, PyFlakes is a static analysis tool that lets you catch static programming errors when you write them, not when you run into them at runtime. And <code>pep8</code> is a Python style checking tool that enforces <a href="http://www.python.org/dev/peps/pep-0008/">PEP8</a> guidelines on your code.</p> <p><a href="http://pypi.python.org/pypi/flake8">Flake8</a>, though, seems to be a much better option to use these days. It integrates both of PEP8 and PyFlakes and even combines it with a cyclomatic complexity checker (which is irrelevant for the Vim plugin, by the way). To install Flake8, simply use:</p> <div class="codehilite"><pre><span class="gp">$</span> pip install flake8 </pre></div> <p>After installing the plugin in Vim, you can add the following command to your <code>.vimrc</code> file to have it executed after every save of a Python source file.</p> <div class="codehilite"><pre>autocmd <span class="nb">BufWritePost</span> *.<span class="k">py</span> <span class="k">call</span> Flake8<span class="p">()</span> </pre></div> <p>To avoid specific error messages from being reported, put a <code># noqa</code> comment at the end of that line.</p> <h2 id="installation">Installation <a href="#installation" rel="bookmark" class="permalink">¶</a></h2> <p>Assuming you already use <a href="https://github.com/tpope/vim-pathogen">vim-pathogen</a> (which you really should), you can simply install the plugin by cloning the <a href="https://github.com/nvie/vim-flake8">repository</a> into the <code>~/.vim/bundle</code> folder.</p> Just a quick post to let you know that I discarded my `vim-pep8` and `vim-pyflakes` Vim plugins yesterday in favor of [vim-flake8](https://github.com/nvie/vim-flake8). 2012-02-14T00:00:00+00:00 http://nvie.com/posts/introducing-times/ Introducing Times 2012-02-08T00:00:00+00:00 <p>Lately I’ve been getting sick of working with datetimes and timezones in Python. The standard library offers many different conversion routines, but does not prescribe a best practice way to deal with them. Luckily, Armin Ronacher did in his article <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/">Dealing with Timezones in Python</a>.</p> <p>The summary is to never ever work with local datetimes. When a local datetime is input, immediately convert it to universal time and only ever store or calculate with those. Only when <em>presenting</em> datetimes to the end user, convert them to local time again.</p> <p>This seems simple enough, alright. But to actually <em>do</em> it in Python, you still have to think about how to implement it correctly. Every. Single. Time. <code>pytz</code> does help a bit here, but it still isn’t trivial. It should be.</p> <p>Meet <a href="https://github.com/nvie/times"><code>Times</code></a>, a very small Python library to deal with conversions from universal to local timezones and vice versa. It’s focused on simplicity and opinionated about what is good practice.</p> <h2 id="example-use">Example use <a href="#example-use" rel="bookmark" class="permalink">¶</a></h2> <p>Imagine you’re building a web app that allows your users to set an alarm. Say that someone in the Netherlands sets an alarm to 9:30 am. You can use <code>times</code> to simplify this:</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">times</span> <span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">datetime</span> <span class="gp">&gt;&gt;&gt; </span> <span class="gp">&gt;&gt;&gt; </span><span class="n">local_time</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="p">(</span><span class="mi">2012</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">universal_time</span> <span class="o">=</span> <span class="n">times</span><span class="o">.</span><span class="n">to_universal</span><span class="p">(</span><span class="n">local_time</span><span class="p">,</span> <span class="s">&#39;Europe/Amsterdam&#39;</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">universal_time</span> <span class="go">datetime.datetime(2012, 2, 3, 8, 30)</span> </pre></div> <p>Now, this <code>universal_time</code> variable is safe to store or calculate with.</p> <p>Once you want to show this date to the user again, simply format it for the given timezone:</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">times</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">universal_time</span><span class="p">,</span> <span class="s">&#39;Europe/Amsterdam&#39;</span><span class="p">)</span> <span class="go">&#39;2012-02-03 09:30:00+0100&#39;</span> </pre></div> <p>If your app allows users to share alerts, it is just as easy to present the alert date to an end user in New Zealand as well:</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">times</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">universal_time</span><span class="p">,</span> <span class="s">&#39;Pacific/Auckland&#39;</span><span class="p">)</span> <span class="go">&#39;2012-02-03 21:30:00+1300&#39;</span> </pre></div> <h2 id="current-time">Current time <a href="#current-time" rel="bookmark" class="permalink">¶</a></h2> <p>If you ever need to record the current time, you can use</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">times</span><span class="o">.</span><span class="n">now</span><span class="p">()</span> <span class="go">datetime.datetime(2012, 2, 2, 16, 4, 40, 283090)</span> </pre></div> <p>Which is actually just an alias to <code>datetime.datetime.utcnow()</code>.</p> <h2 id="converting-from-other-sources">Converting from other sources <a href="#converting-from-other-sources" rel="bookmark" class="permalink">¶</a></h2> <p>I’ve added the ability to create universal times from two other sources: UNIX timestamps and date strings. To use any of these, simply pass them to the <code>to_universal</code> function, like so:</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="go">1328729274.982</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">times</span><span class="o">.</span><span class="n">to_universal</span><span class="p">(</span><span class="mf">1328729274.982</span><span class="p">)</span> <span class="go">datetime.datetime(2012, 2, 8, 19, 27, 54, 982000)</span> </pre></div> <p>Note that UNIX timestamps <em>must</em> be in UTC (which the output of <code>time.time()</code> is). Local UNIX timestamps are not accepted.</p> <p>To create universal times from string representations, <code>Times</code> uses the advanced parser from the <code>python-dateutil</code> library. Time zones are automatically recognized if such info is encoded in the string representation. In any other case, you are required to provide it explicitly. Two examples to illustrate both variants:</p> <div class="codehilite"><pre><span class="gp">&gt;&gt;&gt; </span><span class="c"># Timezone-aware date formats don&#39;t require a source timezone</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">date_str</span> <span class="o">=</span> <span class="s">&#39;2012-02-08 19:27:54+0100&#39;</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">times</span><span class="o">.</span><span class="n">to_universal</span><span class="p">(</span><span class="n">date_str</span><span class="p">)</span> <span class="go">datetime.datetime(2012, 2, 8, 18, 27, 54)</span> <span class="gp">&gt;&gt;&gt; </span><span class="c"># Timezone-less date formats require an explicit source timezone</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">date_str</span> <span class="o">=</span> <span class="s">&#39;2012-02-08 19:27:54&#39;</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">times</span><span class="o">.</span><span class="n">to_universal</span><span class="p">(</span><span class="n">date_str</span><span class="p">,</span> <span class="s">&#39;Asia/Singapore&#39;</span><span class="p">)</span> <span class="go">datetime.datetime(2012, 2, 8, 11, 27, 54)</span> </pre></div> <h2 id="installing">Installing <a href="#installing" rel="bookmark" class="permalink">¶</a></h2> <p><code>Times</code> is on PyPI (<a href="http://pypi.python.org/pypi/times">link</a>), so just <code>pip install times</code> to use it.</p> <p>Of course, you can <a href="http://github.com/nvie/times">fork me on GitHub</a>.</p> <p>As usual, <code>Times</code> is licensed under the liberal terms of the BSD license.</p> Lately I’ve been getting sick of working with datetimes and timezones in Python. The standard library offers many different conversion routines, but does not prescribe a best practice way to deal with them. Luckily, Armin Ronacher did in his article [Dealing with Timezones in Python](http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/). 2012-02-02T00:00:00+00:00 http://nvie.com/posts/chords-lyrics/ Chords + Lyrics 2011-10-22T00:00:00+00:00 <p>It’s been quite a while since I took the time to update this blog. Many things have happened in the meanwhile, though. The most important happening for me is that I launched an iPad app and I founded a company called <a href="http://www.3rdcloud.com">3rd Cloud</a> last week.</p> <h2 id="hello-chords-lyrics">Hello, Chords + Lyrics! <a href="#hello-chords-lyrics" rel="bookmark" class="permalink">¶</a></h2> <p>An annoying problem amateur musicians might be familiar with is that chords or tablature websites all look very differently, format their song data in various formats, and oftentimes are just plain ugly. Oh, and they’re generally paved with ads, too. So to scratch our own itches, I teamed up with <a href="http://twitter.com/jr00n">@jr00n</a> from <a href="http://www.studiowolff.nl">StudioWolff</a> to create <a href="http://www.chordsandlyricsapp.com">Chords + Lyrics</a>.</p> <p>Chords + Lyrics is a simple music manager for your iPad that allows you to easily import songs and lyrics from your favorite chords website (that means: <em>any</em> website—it recognizes the chords semantically):</p> <p class="centered"><img alt="" src="/img/showcase3.png" /></p> <p>Once imported, the chords become editable objects in the form of bubbles, which makes it easy for you to edit or finetune the imported songs. A carefully selected choice of fonts is used to create a readable and uniform look and feel for your song’s chords and lyrics:</p> <p class="centered"><img alt="" src="/img/showcase1.png" /></p> <p>Furthermore, once the editing is done, you can simply take Chords + Lyrics on stage with your band or solo performance and leave your stack of sheet music at home. When the device is rotated into landscape orientation, the user interface transforms into a big music stand that arranges the songs of choice as a stack of virtual music sheets in the order of your playlist:</p> <p class="centered"><img alt="" src="/img/showcase4.png" /></p> <p>You can get a sneak peak of the app by watching this video:</p> <iframe width="560" height="420" src="http://www.youtube.com/embed/pG51bemU0ok?rel=0&amp;hd=1" frameborder="0" allowfullscreen> </iframe> <p>The app is sold at $5.99. Check us out in the <a href="http://itunes.apple.com/us/app/chords-lyrics/id462295346?ls=1&amp;mt=8">App Store</a>.</p> <p class="centered"><a href="http://itunes.apple.com/us/app/chords-lyrics/id462295346?ls=1&amp;mt=8"><img alt="" src="/img/appstore_badge.png" /></a></p> <h2 id="the-role-of-appsterdam">The Role of Appsterdam <a href="#the-role-of-appsterdam" rel="bookmark" class="permalink">¶</a></h2> <p>Jeroen and I met during <a href="http://www.iosdevcamp.org/">iOS Dev Camp</a> last March and immediately were excited with the idea for Chords + Lyrics. We even received the <em>Most Likely to Succeed</em> award from <a href="http://twitter.com/dom">Dom Sogolla</a> and <a href="http://twitter.com/bmf">Mike Lee</a> at the end of those two days, which got us even more excited about the project.</p> <p>We started hacking away at it in our spare time for the next few months. While at the same time, by some kind of lucky coincidence, the same Mike Lee started building an awesome developer community for app developers: <a href="http://www.appsterdam.rs">Appsterdam</a>.</p> <p>Many of our thanks therefore go out to all of the Appsterdammers, in particular Mike and <a href="http://twitter.com/judykitteh">Judy</a>, for inspiring us at the moments we got stuck and for the helpful pieces of advice we got from them. Without the Appsterdam community, the project may have never seen the light of day, or be much less awesome.</p> <p>Let this be the first of many apps!</p> I released my first iPad app to import/manage chords and lyrics. 2011-10-05T00:00:00+00:00 http://nvie.com/posts/a-git-flow-screencast/ A git-flow screencast 2011-05-25T00:00:00+00:00 <p>Mr. <a href="http://www.davebock.com/">Dave Bock</a> of Code Sherpa’s put together a nice screencast demonstrating a few of the most important git-flow features on their <a href="http://www.codesherpas.com/portfolio/publications">publications</a> page.</p> <p class="centered"><a href="http://codesherpas.com/screencasts/on_the_path_gitflow.mov"><img alt="" src="/img/screencast-still.png" /></a></p> <p>Many thanks to Dave for creating this!</p> Mr. [Dave Bock](http://www.davebock.com/) of Code Sherpa’s put together a nice screencast demonstrating a few of the most important git-flow features on their [publications](http://www.codesherpas.com/portfolio/publications) page. 2011-01-27T00:00:00+00:00 http://nvie.com/posts/how-i-boosted-my-vim/ How I boosted my Vim 2010-09-23T00:00:00+00:00 <p>A few weeks ago, I felt inspired by articles from <a href="http://jeffkreeftmeijer.com/2010/stumbling-into-vim/">Jeff Kreeftmeijer</a> and <a href="http://lucumr.pocoo.org/2010/7/29/sharing-vim-tricks">Armin Ronacher</a>. I took some time to configure and fine-tune my Vim environment. A lot of new stuff made it into my <code>.vimrc</code> file and my <code>.vim</code> directory. This blog post is a summary describing what I’ve added and how I use it in my daily work.</p> <p>Before doing anything else, make sure you have the following line in your <code>.vimrc</code> file:</p> <div class="codehilite"><pre><span class="c">&quot; This must be first, because it changes other options as side effect</span> <span class="k">set</span> <span class="nb">nocompatible</span> </pre></div> <h2 id="pathogen">Step 0: make the customization process easier <a href="#pathogen" rel="bookmark" class="permalink">¶</a></h2> <p>Before starting configuring, it’s useful to install <a href="http://www.vim.org/scripts/script.php?script_id=2332">pathogen</a>. Plugins in Vim are files that you drop in subdirectories of your <code>.vim/</code> directory. Many plugins exist of only a single file that should be dropped in <code>.vim/plugin</code>, but some exist of multiple files. For example, they come with documentation, or ship syntax files. In those cases, files need to be dropped into <code>.vim/doc</code> and <code>.vim/syntax</code>. This makes it difficult to remove the plugin afterwards. After installing pathogen, you can simply unzip a plugin distribution into <code>.vim/bundle/myplugin</code>, under which the required subdirectories are created. Removing the plugin, then, is as simple as removing the <code>myplugin</code> directory.</p> <p>So, download <code>pathogen.vim</code>, move it into the <code>.vim/autoload</code> directory (create it if necessary) and add the following lines to your <code>.vimrc</code>, to activate it:</p> <div class="codehilite"><pre><span class="c">&quot; Use pathogen to easily modify the runtime path to include all</span> <span class="c">&quot; plugins under the ~/.vim/bundle directory</span> <span class="k">call</span> pathogen#<span class="k">helptags</span><span class="p">()</span> <span class="k">call</span> pathogen#runtime_append_all_bundles<span class="p">()</span> </pre></div> <p>Next, I’ve remapped the leader key to <code>,</code> (comma) instead of the default <code>\</code> (backslash), just because I like it better. Since in Vim’s default configuration, almost every key is already mapped to a command, there needs to be some sort of standard “free” key where you can place custom mappings under. This is called the “mapleader”, and can be defined like this:</p> <div class="codehilite"><pre><span class="c">&quot; change the mapleader from \ to ,</span> <span class="k">let</span> mapleader<span class="p">=</span><span class="s2">&quot;,&quot;</span> </pre></div> <p>Once that is done, this is a little tweak that is a time-saver while you’re building up your <code>.vimrc</code>. Here, we start using the leader key:</p> <div class="codehilite"><pre><span class="c">&quot; Quickly edit/reload the vimrc file</span> nmap <span class="p">&lt;</span><span class="k">silent</span><span class="p">&gt;</span> <span class="p">&lt;</span>leader<span class="p">&gt;</span>ev :<span class="k">e</span> $MYVIMRC<span class="p">&lt;</span>CR<span class="p">&gt;</span> nmap <span class="p">&lt;</span><span class="k">silent</span><span class="p">&gt;</span> <span class="p">&lt;</span>leader<span class="p">&gt;</span><span class="k">sv</span> :<span class="k">so</span> $MYVIMRC<span class="p">&lt;</span>CR<span class="p">&gt;</span> </pre></div> <p>This effectively maps the <code>,ev</code> and <code>,sv</code> keys to edit/reload <code>.vimrc</code>. (I got this from <a href="http://derekwyatt.org/">Derek Wyatt</a>’s <code>.vimrc</code> file.)</p> <h2 id="change-vim-behaviour">Change Vim behaviour <a href="#change-vim-behaviour" rel="bookmark" class="permalink">¶</a></h2> <p>One particularly useful setting is <code>hidden</code>. Its name isn’t too descriptive, though. It <em>hides</em> buffers instead of <em>closing</em> them. This means that you can have unwritten changes to a file and open a new file using <code>:e</code>, without being forced to write or undo your changes first. Also, undo buffers and marks are preserved while the buffer is open. This is an absolute must-have.</p> <div class="codehilite"><pre><span class="k">set</span> <span class="nb">hidden</span> </pre></div> <p>These are some of the most basic settings that you probably want to enable, too:</p> <div class="codehilite"><pre><span class="k">set</span> <span class="nb">nowrap</span> <span class="c">&quot; don&#39;t wrap lines</span> <span class="k">set</span> <span class="nb">tabstop</span><span class="p">=</span><span class="m">4</span> <span class="c">&quot; a tab is four spaces</span> <span class="k">set</span> <span class="nb">backspace</span><span class="p">=</span>indent<span class="p">,</span><span class="nb">eol</span><span class="p">,</span><span class="k">start</span> <span class="c"> &quot; allow backspacing over everything in insert mode</span> <span class="k">set</span> <span class="nb">autoindent</span> <span class="c">&quot; always set autoindenting on</span> <span class="k">set</span> <span class="nb">copyindent</span> <span class="c">&quot; copy the previous indentation on autoindenting</span> <span class="k">set</span> <span class="k">number</span> <span class="c">&quot; always show line numbers</span> <span class="k">set</span> <span class="nb">shiftwidth</span><span class="p">=</span><span class="m">4</span> <span class="c">&quot; number of spaces to use for autoindenting</span> <span class="k">set</span> <span class="nb">shiftround</span> <span class="c">&quot; use multiple of shiftwidth when indenting with &#39;&lt;&#39; and &#39;&gt;&#39;</span> <span class="k">set</span> <span class="nb">showmatch</span> <span class="c">&quot; set show matching parenthesis</span> <span class="k">set</span> <span class="nb">ignorecase</span> <span class="c">&quot; ignore case when searching</span> <span class="k">set</span> <span class="nb">smartcase</span> <span class="c">&quot; ignore case if search pattern is all lowercase,</span> <span class="c"> &quot; case-sensitive otherwise</span> <span class="k">set</span> <span class="nb">smarttab</span> <span class="c">&quot; insert tabs on the start of a line according to</span> <span class="c"> &quot; shiftwidth, not tabstop</span> <span class="k">set</span> <span class="nb">hlsearch</span> <span class="c">&quot; highlight search terms</span> <span class="k">set</span> <span class="nb">incsearch</span> <span class="c">&quot; show search matches as you type</span> </pre></div> <p>There is a lot more goodness in my <a href="http://github.com/nvie/vimrc/raw/master/vimrc"><code>.vimrc</code></a> file, which is put in there with a lot of love. I’ve commented most of it, too. Feel free to poke around in it.</p> <p>Also, I like Vim to have a large undo buffer, a large history of commands, ignore some file extensions when completing names by pressing Tab, and be silent about invalid cursor moves and other errors.</p> <div class="codehilite"><pre><span class="k">set</span> <span class="k">history</span><span class="p">=</span><span class="m">1000</span> <span class="c">&quot; remember more commands and search history</span> <span class="k">set</span> <span class="nb">undolevels</span><span class="p">=</span><span class="m">1000</span> <span class="c">&quot; use many muchos levels of undo</span> <span class="k">set</span> <span class="nb">wildignore</span><span class="p">=</span>*.swp<span class="p">,</span>*.bak<span class="p">,</span>*.pyc<span class="p">,</span>*.class <span class="k">set</span> <span class="nb">title</span> <span class="c">&quot; change the terminal&#39;s title</span> <span class="k">set</span> <span class="nb">visualbell</span> <span class="c">&quot; don&#39;t beep</span> <span class="k">set</span> <span class="nb">noerrorbells</span> <span class="c">&quot; don&#39;t beep</span> </pre></div> <p>I don't like Vim to ever write a backup file. I prefer <a href="http://git-scm.com/">more modern ways</a> of protecting against data loss.</p> <div class="codehilite"><pre><span class="k">set</span> <span class="nb">nobackup</span> <span class="k">set</span> <span class="nb">noswapfile</span> </pre></div> <p>There have been some passionate responses about this in comments, so a warning may be appropriate here. If you care about recovering after a Vim or terminal emulator crash, or you often load huge files into memory, do <strong>not</strong> disable the swapfile. I personally save/commit so <a href="http://jeffkreeftmeijer.com/2010/git-your-act-together/#commit-all-the-fucking-time">often</a> that the swap file adds nothing. Sometimes I conciously kill a terminal forcefully, and I only find the swap file recovery process annoying.</p> <h2 id="use-file-type-plugins">Use file type plugins <a href="#use-file-type-plugins" rel="bookmark" class="permalink">¶</a></h2> <p>Vim can detect file types (by their extension, or by peeking inside the file). This enabled Vim to load plugins, settings or key mappings that are only useful in the context of specific file types. For example, a Python syntax checker plugin only makes sense in a Python file. Finally, indenting intelligence is enabled based on the syntax rules for the file type.</p> <div class="codehilite"><pre><span class="k">filetype</span> plugin indent <span class="k">on</span> </pre></div> <p>To set some file type specific settings, you can now use the following:</p> <div class="codehilite"><pre>autocmd <span class="k">filetype</span> python <span class="k">set</span> <span class="nb">expandtab</span> </pre></div> <p>To remain compatible with older versions of Vim that do not have the <code>autocmd</code> functions, always wrap those functions inside a block like this:</p> <div class="codehilite"><pre><span class="k">if</span> has<span class="p">(</span><span class="s1">&#39;autocmd&#39;</span><span class="p">)</span> ... <span class="k">endif</span> </pre></div> <h2 id="enable-syntax-highlighting">Enable syntax highlighting <a href="#enable-syntax-highlighting" rel="bookmark" class="permalink">¶</a></h2> <p>Somewhat related to the file type plugins is the syntax highlighting of different types of source files. Vim uses syntax definitions to highlight source code. Syntax definitions simply declare where a function name starts, which pieces are commented out and what are keywords. To color them, Vim uses colorschemes. You can load custom color schemes by placing them in <code>.vim/colors</code>, then load them using the <code>colorscheme</code> command. You have to try what you like most. I like <a href="http://hcalves.deviantart.com/art/Mustang-Vim-Colorscheme-98974484">mustang</a> a lot.</p> <div class="codehilite"><pre><span class="k">if</span> &amp;<span class="nb">t_Co</span> <span class="p">&gt;=</span> <span class="m">256</span> <span class="p">||</span> has<span class="p">(</span><span class="s2">&quot;gui_running&quot;</span><span class="p">)</span> <span class="k">colorscheme</span> mustang <span class="k">endif</span> <span class="k">if</span> &amp;<span class="nb">t_Co</span> <span class="p">&gt;</span> <span class="m">2</span> <span class="p">||</span> has<span class="p">(</span><span class="s2">&quot;gui_running&quot;</span><span class="p">)</span> <span class="c"> &quot; switch syntax highlighting on, when the terminal has colors</span> <span class="nb">syntax</span> <span class="k">on</span> <span class="k">endif</span> </pre></div> <p>In this case, mustang is only loaded if the terminal emulator Vim runs in supports at least 256 colors (or if you use the GUI version of Vim).</p> <p><strong>Hint</strong>: If you’re using a terminal emulator that can show 256 colors, try setting <code>TERM=xterm-256color</code> in your terminal configuration or in your shell’s .rc file.</p> <h2 id="change-editing-behaviour">Change editing behaviour <a href="#change-editing-behaviour" rel="bookmark" class="permalink">¶</a></h2> <p>When you write a lot of code, you probably want to obey certain style rules. In some programming languages (like Python), whitespace is important, so you may not just swap tabs for spaces and even the number of spaces is important.</p> <p>Vim can highlight whitespaces for you in a convenient way:</p> <div class="codehilite"><pre><span class="k">set</span> <span class="nb">list</span> <span class="k">set</span> <span class="nb">listchars</span><span class="p">=</span><span class="k">tab</span>:<span class="p">&gt;</span>.<span class="p">,</span>trail:.<span class="p">,</span>extends:#<span class="p">,</span>nbsp:. </pre></div> <p>This line will make Vim set out tab characters, trailing whitespace and invisible spaces visually, and additionally use the <code>#</code> sign at the end of lines to mark lines that extend off-screen. For more info, see <code>:h listchars</code>.</p> <p>In some files, like HTML and XML files, tabs are fine and showing them is really annoying, you can disable them easily using an <code>autocmd</code> declaration:</p> <div class="codehilite"><pre>autocmd <span class="k">filetype</span> html<span class="p">,</span>xml <span class="k">set</span> <span class="nb">listchars</span><span class="p">-=</span><span class="k">tab</span>:<span class="p">&gt;</span>. </pre></div> <p>One caveat when setting <code>listchars</code>: if nothing happens, you have probably not enabled <code>list</code>, so try <code>:set list</code>, too.</p> <h2 id="pasting-large-amounts-of-text-into-vim">Pasting large amounts of text into Vim <a href="#pasting-large-amounts-of-text-into-vim" rel="bookmark" class="permalink">¶</a></h2> <p>Every Vim user likes to enable auto-indenting of source code, so Vim can intelligently position you cursor on the next line as you type. This has one big ugly consequence however: when you paste text into your terminal-based Vim with a right mouse click, Vim cannot know it is coming from a paste. To Vim, it looks like text entered by someone who can type incredibly fast :) Since Vim thinks this is regular key strokes, it applies all auto-indenting and auto-expansion of defined abbreviations to the input, resulting in often cascading indents of paragraphs.</p> <p>There is an easy option to prevent this, however. You can temporarily switch to “paste mode”, simply by setting the following option:</p> <div class="codehilite"><pre><span class="k">set</span> <span class="nb">pastetoggle</span><span class="p">=&lt;</span>F2<span class="p">&gt;</span> </pre></div> <p>Then, when in insert mode, ready to paste, if you press <code>&lt;F2&gt;</code>, Vim will switch to paste mode, disabling all kinds of smartness and just pasting a whole buffer of text. Then, you can disable paste mode again with another press of <code>&lt;F2&gt;</code>. Nice and simple. Compare paste mode disabled vs enabled:</p> <p><img alt="" class="left" src="/img/ugly-paste.png" style="margin-left: -40px" /> <img alt="" class="right" src="/img/better-paste.png" style="margin-right: -40px" /></p> <p style="clear: both">Another great trick I read in a <a href="http://www.reddit.com/r/programming/comments/ddbuc/how_i_boosted_my_vim/c0zelsm">reddit comment</a> is to use <code>&lt;C-r&gt;+</code> to paste right from the OS paste board. Of course, this only works when running Vim locally (i.e. not over an SSH connection).</p> <h2 id="enable-the-mouse">Enable the mouse <a href="#enable-the-mouse" rel="bookmark" class="permalink">¶</a></h2> <p>While using the mouse is considered a deadly sin among Vim users, there <em>are</em> a few features about the mouse that can really come to your advantage. Most notably—scrolling. In fact, it’s the only thing I use it for.</p> <p>Also, if you are a rookie Vim user, setting this value will make your Vim experience definitively feel more natural.</p> <p>To enable the mouse, use:</p> <div class="codehilite"><pre><span class="k">set</span> <span class="nb">mouse</span><span class="p">=</span><span class="k">a</span> </pre></div> <p>However, this comes at one big disadvantage: when you run Vim inside a terminal, the terminal itself cannot control your mouse anymore. Therefore, you cannot select text anymore with the terminal (to copy it to the system clipboard, for example).</p> <p>To be able to have the best of both worlds, I wrote this simple Vim plugin: <a href="http://github.com/nvie/vim-togglemouse">vim-togglemouse</a>. It maps <code>&lt;F12&gt;</code> to toggle your mouse “focus” between Vim and the terminal.</p> <p>Small plugins like these are really useful, yet have the additional benefit of lowering the barrier of learning the Vim scripting language. At the core, this plugin exists of only one simple function:</p> <div class="codehilite"><pre><span class="k">fun</span><span class="p">!</span> s:ToggleMouse<span class="p">()</span> <span class="k">if</span> <span class="p">!</span>exists<span class="p">(</span><span class="s2">&quot;s:old_mouse&quot;</span><span class="p">)</span> <span class="k">let</span> s:old_mouse <span class="p">=</span> <span class="s2">&quot;a&quot;</span> <span class="k">endif</span> <span class="k">if</span> &amp;<span class="nb">mouse</span> <span class="p">==</span> <span class="s2">&quot;&quot;</span> <span class="k">let</span> &amp;<span class="nb">mouse</span> <span class="p">=</span> s:old_mouse echo <span class="s2">&quot;Mouse is for Vim (&quot;</span> . &amp;<span class="nb">mouse</span> . <span class="s2">&quot;)&quot;</span> <span class="k">else</span> <span class="k">let</span> s:old_mouse <span class="p">=</span> &amp;<span class="nb">mouse</span> <span class="k">let</span> &amp;<span class="nb">mouse</span><span class="p">=</span><span class="s2">&quot;&quot;</span> echo <span class="s2">&quot;Mouse is for terminal&quot;</span> <span class="k">endif</span> <span class="k">endfunction</span> </pre></div> <h2 id="get-efficient-shortcut-mappings">Get efficient: shortcut mappings <a href="#get-efficient-shortcut-mappings" rel="bookmark" class="permalink">¶</a></h2> <p>The following trick is a really small one, but a super-efficient one, since it strips off two full keystrokes from almost every Vim command:</p> <div class="codehilite"><pre><span class="nb">nnoremap</span> ; : </pre></div> <p>For example, to save a file, you type <code>:w</code> normally, which means:</p> <ol> <li>Press and hold Shift</li> <li>Press <code>;</code></li> <li>Release the Shift key</li> <li>Press <code>w</code></li> <li>Press Return</li> </ol> <p>This trick strips off steps 1 and 3 for <strong>each</strong> Vim command. It takes some times for your muscle memory to get used to this new <code>;w</code> command, but once you use it, you don’t want to go back!</p> <p>I also find this key binding very useful, since I like to reformat paragraph text often. Just set your cursor inside a paragraph and press <code>Q</code> (or select a visual block and press <code>Q</code>).</p> <div class="codehilite"><pre><span class="c">&quot; Use Q for formatting the current paragraph (or selection)</span> vmap Q gq nmap Q gqap </pre></div> <p>If you are still getting used to Vim and want to force yourself to stop using the arrow keys, add this:</p> <div class="codehilite"><pre>map <span class="p">&lt;</span><span class="k">up</span><span class="p">&gt;</span> <span class="p">&lt;</span>nop<span class="p">&gt;</span> map <span class="p">&lt;</span>down<span class="p">&gt;</span> <span class="p">&lt;</span>nop<span class="p">&gt;</span> map <span class="p">&lt;</span><span class="k">left</span><span class="p">&gt;</span> <span class="p">&lt;</span>nop<span class="p">&gt;</span> map <span class="p">&lt;</span><span class="k">right</span><span class="p">&gt;</span> <span class="p">&lt;</span>nop<span class="p">&gt;</span> </pre></div> <p>If you like long lines with line wrapping enabled, this solves the problem that pressing down jumpes your cursor “over” the current line to the next line. It changes behaviour so that it jumps to the next row in the editor (much more natural):</p> <div class="codehilite"><pre><span class="nb">nnoremap</span> <span class="k">j</span> gj <span class="nb">nnoremap</span> <span class="k">k</span> gk </pre></div> <p>When you start to use Vim more professionally, you want to work with multiple windows open. Navigating requires you to press <code>C-w</code> first, then a navigation command (h, j, k, l). This makes it easier to navigate focus through windows:</p> <div class="codehilite"><pre><span class="c">&quot; Easy window navigation</span> map <span class="p">&lt;</span>C<span class="p">-</span><span class="k">h</span><span class="p">&gt;</span> <span class="p">&lt;</span>C<span class="p">-</span><span class="k">w</span><span class="p">&gt;</span><span class="k">h</span> map <span class="p">&lt;</span>C<span class="p">-</span><span class="k">j</span><span class="p">&gt;</span> <span class="p">&lt;</span>C<span class="p">-</span><span class="k">w</span><span class="p">&gt;</span><span class="k">j</span> map <span class="p">&lt;</span>C<span class="p">-</span><span class="k">k</span><span class="p">&gt;</span> <span class="p">&lt;</span>C<span class="p">-</span><span class="k">w</span><span class="p">&gt;</span><span class="k">k</span> map <span class="p">&lt;</span>C<span class="p">-</span><span class="k">l</span><span class="p">&gt;</span> <span class="p">&lt;</span>C<span class="p">-</span><span class="k">w</span><span class="p">&gt;</span><span class="k">l</span> </pre></div> <p>Tired of clearing highlighted searches by searching for “ldsfhjkhgakjks”? Use this:</p> <div class="codehilite"><pre>nmap <span class="p">&lt;</span><span class="k">silent</span><span class="p">&gt;</span> <span class="p">,</span>/ :<span class="k">nohlsearch</span><span class="p">&lt;</span>CR<span class="p">&gt;</span> </pre></div> <p>I used to have it mapped to <code>:let</code>/=“”<CR><code>, but some users kindly pointed out that it is better to use</code>:nohlsearch@, because it keeps the search history intact.</p> <p>It clears the search buffer when you press <code>,/</code></p> <p>Finally, a trick by <a href="http://forrst.com/posts/Use_w_to_sudo_write_a_file_with_Vim-uAN">Steve Losh</a> for when you forgot to <code>sudo</code> before editing a file that requires root privileges (typically <code>/etc/hosts</code>). This lets you use <code>w!!</code> to do that <strong>after</strong> you opened the file already:</p> <div class="codehilite"><pre>cmap <span class="k">w</span><span class="p">!!</span> <span class="k">w</span> <span class="p">!</span>sudo tee % <span class="p">&gt;</span><span class="sr">/dev/</span>null </pre></div> <h2 id="other-cool-plugins">Other cool plugins <a href="#other-cool-plugins" rel="bookmark" class="permalink">¶</a></h2> <p>In order to make the article not any more longer than it already is, here’s a list of other plugins that are really worth checking out (I use each of them regularly):</p> <ul> <li> <p><a href="http://www.vim.org/scripts/script.php?script_id=1408">localrc</a>: lets you load specific Vim settings for any file in the same directory (or a subdirectory thereof). Comes in super handy for project-wide settings.</p> </li> <li> <p><a href="http://kien.github.io/ctrlp.vim/">CtrlP</a>: lets you open files or switch buffers quickly using fuzzy search. I'd highly recommend it.</p> </li> </ul> <h2 id="other-resources">Other resources <a href="#other-resources" rel="bookmark" class="permalink">¶</a></h2> <p>Some of the resources from where I have collected inspiration for my <code>.vimrc</code> file, plugins, and tricks:</p> <ul> <li><a href="http://vimcasts.org/">Vimcasts</a></li> <li><a href="http://lococast.net/">Lococast</a></li> <li><a href="http://vimeo.com/user1690209/videos">Derek Wyatt’s videos</a> (on Vimeo)</li> <li>Steve Losh blogged about <a href="http://stevelosh.com/blog/2010/09/coming-home-to-vim/">moving back to Vim</a> and has some great tips and tricks.</li> </ul> <p>I hope you like these tips. You can have a look at my full Vim configuration in my <a href="http://github.com/nvie/vimrc">Github repo</a>.</p> Where I lay out the recent changed I made to my Vim setup. 2010-09-14T00:00:00+00:00 http://nvie.com/posts/a-whole-new-blog/ A whole new blog 2010-09-13T00:00:00+00:00 <p>Finally, I’ve made the move to a static blog engine! I’m using <a href="http://nanoc.stoneship.org/">nanoc</a> now (bye bye WordPress). nanoc is a very flexible and customizable static site generator, written by <a href="http://twitter.com/ddfreyne">Denis Defreyne</a>.</p> <p>As with all static site generators, nanoc lets you write your source files in a simple markup language. Out of the box, nanoc offers you the choice of using Markdown, Textile, reStructuredText or plain HTML (with or without embedded Ruby). In fact, nanoc is nothing more than a generator honoring a <code>Rules</code>-file that tells it how to compile, layout and route the site’s items.</p> <h2 id="compiling-items">Compiling items <a href="#compiling-items" rel="bookmark" class="permalink">¶</a></h2> <p>An “item” is a file on your website. It can be any kind of file, like a web site page (HTML), an image, a JavaScript or CSS file or an RSS feed. During the compile phase, you specify which sequential actions should be performed on the <em>content</em> of that item. These actions are called <strong>filters</strong>. Some examples of filters are an embedded ruby filter, a <a href="http://redcloth.org/">Textile-to-HTML</a> converter, a <a href="http://lesscss.org/">less</a> compiler, or minify <a href="http://code.google.com/p/rainpress/">CSS</a>. Filters can be chained, for example:</p> <div class="codehilite"><pre><span class="n">compile</span> <span class="s1">&#39;/static/css/*/&#39;</span> <span class="k">do</span> <span class="c1"># compress CSS :)</span> <span class="n">filter</span> <span class="ss">:less</span> <span class="n">filter</span> <span class="ss">:rainpress</span> <span class="k">end</span> </pre></div> <p>Which turns <code>.less</code>-files into compressed CSS:</p> <p><img alt="" src="/img/less2css.png" /></p> <p>Any filter you can imagine, nanoc can handle. nanoc comes with a lot of filters <a href="http://nanoc.stoneship.org/docs/4-basic-concepts/#filters">out of the box</a>, but even <a href="http://nanoc.stoneship.org/docs/5-advanced-concepts/#writing-filters">writing your own</a> filters really is a piece of cake.</p> <h2 id="routing-items">Routing items <a href="#routing-items" rel="bookmark" class="permalink">¶</a></h2> <p>After compiling (i.e. transforming content through filters) comes the routing of the items. This is a means of assigning file names to compiled content. nanoc calculates default files names from the input, but you can use this to influence the default naming. A special case is where you set the route to <code>Nil</code> which doesn’t write the file at all. I use this to test draft posts locally, like this (oh, did I mention the <code>Rules</code> file is 100% Ruby?):</p> <div class="codehilite"><pre><span class="n">route</span> <span class="s1">&#39;/posts/*/&#39;</span> <span class="k">do</span> <span class="k">if</span> <span class="vg">$include_drafts</span> <span class="ow">or</span> <span class="vi">@item</span><span class="o">[</span><span class="ss">:published</span><span class="o">]</span> <span class="k">then</span> <span class="s1">&#39;/posts/&#39;</span> <span class="o">+</span> <span class="vi">@item</span><span class="o">.</span><span class="n">slug</span> <span class="o">+</span> <span class="s1">&#39;/index.html&#39;</span> <span class="k">end</span> <span class="k">end</span> </pre></div> <h2 id="laying-out-items">Laying out items <a href="#laying-out-items" rel="bookmark" class="permalink">¶</a></h2> <p>Finally, layouts are applied. Layouts are kind of templates that can be used to “frame” the item’s contents. This is typically used for HTML files only, but isn’t limited to it. For example, the blog posts are compiled into (partial) HTML, and the layout rules put the site’s container HTML around it, adding CSS styling, jQuery scripts, the header, sidebars and footer and Google Analytics tracking (these go for each page). There’s a special extra layout rule for blog post pages, which additionally adds Disqus comments.</p> <h2 id="summary">Summary <a href="#summary" rel="bookmark" class="permalink">¶</a></h2> <p>Each build of this blog also automatically:</p> <ul> <li>Converts <a href="http://redcloth.org/">Textile</a> content to HTML</li> <li>Highlights syntax using <a href="http://pygments.org/">pygments</a></li> <li>Converts <a href="http://lesscss.org/">less</a> to CSS</li> <li>Minifies <a href="http://code.google.com/p/rainpress/">CSS</a></li> <li>Minifies <a href="http://code.google.com/closure/compiler/">JavaScript</a></li> <li><a href="http://www.graphicsmagick.org/convert.html">Downsizes</a> source images</li> <li>Generates redirect pages for alternative (old-style) URL’s (for user that have existing bookmarks to old WordPress URL’s)</li> <li>Generates a new blog post <a href="http://nanoc.stoneship.org/docs/api/3.1/Nanoc3/Helpers/Blogging.html">RSS feed</a></li> </ul> <p>In short, now nanoc is fully configured to my wishes, I can simply focus on writing <strong>blog content</strong>, without preparing image content (it is done automatically), and without having to choose between either a “WYSIWYG” editor or writing HTML manually. And I can do it in an offline fashion, too, which was one my main complaints about WordPress.</p> <p>So I’m happy.</p> <p>Oh, and since I have been converting my blog anyway, I also created a new look and feel for it. I hope you like it. Feel free to comment.</p> Finally, I've made the move to a static blog engine! I'm using Nanoc now. Nanoc is a very flexible and customizable static site generator, written by Denis Defreyne. As with all static site generators, nanoc lets you write your source files in a simple markup language. However, nanoc is much more flexible and customizable than most of the others out there. Let me show you a sneak peak of its internals. 2010-09-13T00:00:00+00:00 http://nvie.com/posts/an-upgrade-of-gitflow/ An upgrade of gitflow 2010-03-04T00:00:00+00:00 <p>Last week, I silently tagged <a href="http://github.com/nvie/gitflow/tree/0.2">gitflow 0.2</a>. The most important changes since 0.1 are:</p> <ul> <li>Order of arguments changed to have a more “gitish” subcommand structure. For example, you now say: <code>git flow feature start myfeature</code></li> <li>Better initializer. <code>git flow init</code> now prompts interactively to set up a gitflow enabled repo.</li> <li>Added a command to list all feature/release/hotfix/support branches, e.g.: <code>git flow feature list</code></li> <li>Made all merge/rebase operations failsafe, providing a non-destructive workflow in case of merge conflicts.</li> <li>Easy diff’ing of all changes on a specific (or the current) feature branch: <code>git flow feature diff [feature]</code></li> <li>Add support for feature branch rebasing: <code>git flow feature rebase</code></li> <li>Some subactions now take name prefixes as their arguments, for convenience. For example, if you have feature branches called “experimental”, “refactoring” and “feature-X”, you could say: <code>git flow feature finish ref</code><br> And gitflow will know you mean the “refactoring” feature branch.<br> These actions are: <code>finish</code>, <code>diff</code> and <code>rebase</code>.</li> <li>Much better overall sanity checking.</li> <li>Better portability (POSIX compliant code)</li> <li>Better (more portable) flag parsing using Kate Ward’s <a href="http://code.google.com/p/shflags/">shFlags</a>.</li> <li>Improved installer. To install <code>git flow</code> as a first-class Git subcommand, simply type: <code>sudo make install</code></li> <li>Major and minor bug fixes.</li> </ul> <p>That’s all for now.</p> Last week, I silently tagged gitflow 0.2. These are the most important changes since 0.1. 2010-03-04T00:00:00+00:00 http://nvie.com/posts/gitflow-01-released/ gitflow 0.1 released 2010-01-26T00:00:00+00:00 <p>After the overwhelming attention and feedback on the <a href="/posts/a-successful-git-branching-model/">Git branching model post</a>, a general consensus was that this workflow would benefit from some form of proper scriptability. The workflow works seamlessly if you perform the steps involved manually, but hey… manually is manually, really.</p> <blockquote> <p><strong>UPDATE 2/4/2010</strong>: I recommend NOT USING this very early release, but to jump on the <a href="http://github.com/nvie/gitflow/tree/develop">current develop tip</a>, which is much more mature. Release 0.2 is coming very soon.</p> </blockquote> <p>An assisting tool (dubbed <code>gitflow</code>) was therefore created to provide simple, high-level commands to adopt the workflow into your own software development process. It’s free and it’s open source. Feel free to contribute to it if you like.</p> <blockquote> <p>Fork me on Github: <a href="http://github.com/nvie/gitflow">http://github.com/nvie/gitflow</a></p> </blockquote> <p>Since this morning, the first working <a href="http://github.com/nvie/gitflow/downloads">release 0.1</a> was tagged, albeit very basic.</p> <h2 id="a-quick-walkthrough">A quick walkthrough <a href="#a-quick-walkthrough" rel="bookmark" class="permalink">¶</a></h2> <p>The <code>gitflow</code> script essentially features six subcommands: paired start/finish commands for managing the different types of branches from the originating article:</p> <ul> <li>Feature branches:</li> <li><code>gitflow start feature &lt;myfeature&gt;</code></li> <li><code>gitflow finish feature &lt;myfeature&gt;</code></li> <li>Release branches:</li> <li><code>gitflow start release &lt;version-id&gt;</code></li> <li><code>gitflow finish release@ &lt;version-id&gt;</code></li> <li>Hotfix branches:</li> <li><code>gitflow start hotfix &lt;version-id&gt;</code></li> <li><code>gitflow finish hotfix &lt;version-id&gt;</code></li> </ul> <p>Each of these scripts exactly reports what actions were taken and what follow-up actions are required by the user. This output will be polished in future versions to improve the <a href="http://en.wikipedia.org/wiki/User_experience_design">UX</a> . An example output:</p> <div class="codehilite"><pre><span class="gp">$</span> gitflow finish feature foo <span class="go">Branches &#39;develop&#39; and &#39;origin/develop&#39; have diverged.</span> <span class="go">And local branch &#39;develop&#39; is ahead of &#39;origin/develop&#39;.</span> <span class="go">Switched to branch &quot;develop&quot;</span> <span class="go">Your branch is ahead of &#39;origin/develop&#39; by 12 commits.</span> <span class="go">Merge made by recursive.</span> <span class="go"> README | 2 ++</span> <span class="go"> 1 files changed, 2 insertions(+), 0 deletions(-)</span> <span class="go">Deleted branch foo (cd3effb).</span> <span class="go">Summary of actions:</span> <span class="go">- The feature branch &#39;foo&#39; was merged into &#39;develop&#39;</span> <span class="go">- Feature branch &#39;foo&#39; has been removed</span> <span class="go">- You are now on branch &#39;develop&#39;</span> </pre></div> <h2 id="limitations">Limitations <a href="#limitations" rel="bookmark" class="permalink">¶</a></h2> <p>The script is very limited at the moment yet, but future versions will fix that, too. Some of the main limitations:</p> <ul> <li>Branch names (<code>master</code>, <code>develop</code>) and the remote repo name (<code>origin</code>) are currently fixed.</li> <li>There is no support for dealing with merge conflicts yet.</li> <li>There is no support for <code>support-*</code> branches.</li> <li>There is no documentation.</li> <li>There is no installer.</li> </ul> <p>However, as this post is written, some of the limitations are already taken care of by community members. Power to the open source!</p> After the overwhelming attention and feedback on the Git branching model post, a general consensus was that this workflow would benefit from some form of proper scriptability. This post proposes the initial version of a tool I called git-flow. 2010-01-26T00:00:00+00:00 http://nvie.com/posts/auto-generate-classes-for-your-core-data-data-model-revisited/ Auto-generate classes for your Core Data data model, revisited 2009-09-19T00:00:00+00:00 <p>A few months ago, I wrote about <a href="/posts/automatically-generate-classes-for-your-core-data-data-model/">automatically generating classes for your Core Data entities</a> and how to automate Xcode using users scripts, such that, when your model changed, you only needed to run your custom script again and your intermediate model files would reflect the new situation.</p> <p>Well, the guys from the <a href="http://github.com/rentzsch/mogenerator">mogenerator</a> project have come up with a far superior solution in the mean time. The newest version of mogenerator comes with an Xcode plugin named Xmo’d, which monitors your <code>*.xcdatamodel</code> file for changes and, as soon as it changes, regenerates all of the neccessary files.</p> <p><strong>This means that there is officially no more reason not to use mogenerator.</strong></p> <p>To set it up, download the installer package from their (improved) <a href="http://rentzsch.github.com/mogenerator/">project website</a> and install it. (Before installing, please read the important release note about the renamed method <code>+newInManagedObjectContext:</code>.)</p> <p>When installed, all you need to do is Command-click your <code>*.xcdatamodel</code> file, click Get Info, switch to the Comments tab and add the string “xmod” to the comment field. This is the trigger for Xmo’d to start (re)generating your machine-classes (the underscored class files) when the data model changes. Brilliant!</p> <p><img alt="" src="/img/comment-field.png" /></p> <p>Oh, the default location at which the generated files will be emitted, is in a folder named after your project, right next to where your <code>*.xcdatamodel</code> already sits:</p> <p><img alt="" src="/img/emission-location.png" /></p> <p>Enjoy it and spread the word!</p> A few months ago, I wrote about [automatically generating classes for your Core Data entities][prev] and how to automate Xcode using users scripts, such that, when your model changed, you only needed to run your custom script again and your intermediate model files would reflect the new situation. 2009-09-19T00:00:00+00:00 http://nvie.com/posts/automatically-generate-classes-for-your-core-data-data-model/ Automatically generate classes for your Core Data data model 2009-06-30T00:00:00+00:00 <p>When designing a Core Data data model for your Xcode projects, you can choose to create Objective-C object wrappers for your entities, so that you can profit from type-safe code. The normal, tedious, workflow for this is that you select each entity from the model designer, select all of its attributes and relationships, Ctrl-click it and from the contextual menu first select “Copy Obj-C 2.0 Method Declarations To Clipboard”, paste it into the appropriate class header file, then do the same thing for the method implementations in the class implementation file. Waaaaaay too much work. Not to mention the manual copy-pastes are really hard to keep in sync once you start adding functionality to these class files, since you don’t want to overwrite those additions, but you want to keep replacing everything else.</p> <h2 id="meet-mogenerator">Meet mogenerator <a href="#meet-mogenerator" rel="bookmark" class="permalink">¶</a></h2> <p>Fortunately, there is a great way for automating this process, using mogenerator. The tool can be downloaded as a <a href="http://aralbalkan.com/2152">DMG installer</a> (Aral Balkan’s blog mentions a workaround for older Xcode versions, but for Xcode 3.1.3 it worked out of the box for me), or you can checkout the sources from <a href="http://github.com/rentzsch/mogenerator/">github</a> and build it yourself.</p> <p>The mogenerator command line tool eases this generation process by reading the <code>*.xcdatamodel</code> file and generating both class files and intermediate class files for each entity. The intermediate classes (called <em>machine</em> classes) are continuously overwritten by subsequent regenerations, so you should never edit the contents of these files. The actual model object classes (called <em>human</em> classes) inherit from those intermediate classes with a default empty implementation, allowing for all manual extensions.</p> <p>For example, when you design a model with two entities Foo and Bar, mogenerator can be invokes as follows:</p> <div class="codehilite"><pre><span class="gp">$</span> mogenerator -m MyDocument.xcdatamodel -M Entities -H Model </pre></div> <p>The flag <code>-m</code> sets the input model file, while <code>-M</code> and <code>-H</code> specify the output directories where the machine and human classes should be generated respectively.</p> <p>This does a few things:</p> <ul> <li>In the Entities subdirectory, there will be generated header and implementation files for NSManagedObject subclasses called <code>_Foo</code> and <code>_Bar</code>;</li> <li>In the Model subdirectory, there will be generated classes called <code>Foo</code> and <code>Bar</code>—respective subclasses of <code>_Foo</code> and <code>_Bar</code>. These are only created if not available yet. Otherwise, they are left as is.</li> </ul> <h2 id="wrapping-it-up">Wrapping it up <a href="#wrapping-it-up" rel="bookmark" class="permalink">¶</a></h2> <p>The trick of how mogenerator works is that you can run the script as often as you want. After every change in your model, you’ll want to re-run the generation again to update the machine classes. You could easily leave Xcode, switch over to Terminal and issue the command above. But you’ll get quite tired of that after a few times.</p> <p>Therefore, I’ve written a custom user script that can be added to Xcode (see figure), which does the following:</p> <ul> <li>You can configure the output directories in the first lines of the script. There is no per-project configuration, so choose them as you would like to use them with all your projects;</li> <li>Mind that these generated files are not automatically included in your Xcode project. Drag them there once and ideally put the machine generated classes into a group under “Other resource”, so you never have to see them again. Whenever you add a new class to your model, new files will be generated, so again you must drag the new files to reference those, of course!</li> <li>The script can be run with any file in the project opened. It starts out with that file and walks up the directory tree to search for your Xcode project. If found, it executes all the rest from your project directory. (Suggestions are welcome, I could not find a better implementation since a variable like <code>%%%{PBXProjectPath}%%%</code> does not seem to exist.)</li> <li>It invokes mogenerator to generate all model classes for the project. It is smart enough to detect whether you are using Brian Webster’s <a href="http://www.fatcatsoftware.com/blog/2008/per-object-ordered-relationships-using-core-data">BWOrderedManagedObject</a> in your project. If so, your generated machine classes will inherit from BWOrderedManagedObject instead of NSManagedObject.</li> </ul> <p class="centered"><img alt="" src="/img/set-user-script.png" /></p> <p>To add this script to Xcode, open the menu Scripts (the icon) > Edit User Scripts… Click the “+”-button on the bottom-left and select “New shell script”. Set the values for Input, Directory, Output and Errors as in the screenshot above, then copy-paste the script below into the code window. Add a nice keyboard shortcut to this action to top it off :-) I’ve chosen ⌥⌘G for this.</p> <p>Please feel free to leave any comments if this helped you.</p> <div class="codehilite"><pre><span class="c">#!/bin/sh</span> <span class="c">#</span> <span class="c"># Automatic (re)generation of model classes for all *.xcdatamodel files.</span> <span class="c"># Written by Vincent Driessen</span> <span class="c">#</span> <span class="c"># You are free to use this script in any way.</span> <span class="c"># The original blog post is http://nvie.com/archives/263</span> <span class="c">#</span> <span class="c"># Define output directories</span> <span class="nv">MACHINE_DIR</span><span class="o">=</span><span class="s2">&quot;Entities&quot;</span> <span class="nv">MODEL_DIR</span><span class="o">=</span><span class="s2">&quot;Model&quot;</span> <span class="c"># Look for the Xcode project directory for this file</span> <span class="nb">cd</span> <span class="sb">`</span>dirname <span class="s2">&quot;%%%{PBXFilePath}%%%&quot;</span><span class="sb">`</span> <span class="k">while</span> <span class="o">[</span> <span class="sb">`</span>ls -d *.xcodeproj 2&gt;/dev/null <span class="p">|</span> wc -l<span class="sb">`</span> -eq <span class="m">0</span> <span class="o">]</span><span class="p">;</span> <span class="k">do</span> <span class="nb">cd</span> .. <span class="k">if</span> <span class="o">[</span> <span class="s2">&quot;`pwd`&quot;</span> <span class="o">=</span> <span class="s2">&quot;/&quot;</span> <span class="o">]</span><span class="p">;</span> <span class="k">then</span> <span class="nb">echo</span> <span class="s2">&quot;No Xcode project found.&quot;</span> <span class="nb">exit </span>1 <span class="k">fi</span> <span class="k">done</span> <span class="nb">echo</span> <span class="s2">&quot;Project directory is `pwd`&quot;</span> <span class="c">#</span> <span class="c"># Check to see whether the base class is just a default (NSManagedObject) or</span> <span class="c"># maybe Brian Webster&#39;s excellent BWOrderedManagedObject.</span> <span class="c"># http://fatcatsoftware.com/blog/2008/per-object-ordered-relationships-using-core-data</span> <span class="c">#</span> <span class="c"># NOTE:</span> <span class="c"># The check really is quite arbitrary: if there exists a file called</span> <span class="c"># BWOrderedManagedObject.h somewhere below the project root directory, we</span> <span class="c"># assume that we want to use this as the base class for all generated classes.</span> <span class="c">#</span> <span class="nv">EXTRA_FLAGS</span><span class="o">=</span> <span class="k">if</span> <span class="o">[</span> <span class="sb">`</span>find . -name BWOrderedManagedObject.h <span class="p">|</span> wc -l<span class="sb">`</span> -gt <span class="m">0</span> <span class="o">]</span><span class="p">;</span> <span class="k">then</span> EXTRA_FLAGS+<span class="o">=</span><span class="s2">&quot;--base-class BWOrderedManagedObject&quot;</span> <span class="k">fi</span> <span class="c"># Generate the model classes using mogenerator</span> <span class="k">for</span> model in <span class="sb">`</span>find . -name <span class="s1">&#39;*.xcdatamodel&#39;</span><span class="sb">`</span><span class="p">;</span> <span class="k">do</span> <span class="c"># The output directories have to exist, so create them</span> mkdir -p <span class="s2">&quot;</span><span class="si">${</span><span class="nv">MACHINE_DIR</span><span class="si">}</span><span class="s2">&quot;</span> <span class="s2">&quot;</span><span class="si">${</span><span class="nv">MODEL_DIR</span><span class="si">}</span><span class="s2">&quot;</span> mogenerator <span class="si">${</span><span class="nv">EXTRA_FLAGS</span><span class="si">}</span> -m <span class="s2">&quot;</span><span class="si">${</span><span class="nv">model</span><span class="si">}</span><span class="s2">&quot;</span> -M <span class="s2">&quot;</span><span class="si">${</span><span class="nv">MACHINE_DIR</span><span class="si">}</span><span class="s2">&quot;</span> -H <span class="s2">&quot;</span><span class="si">${</span><span class="nv">MODEL_DIR</span><span class="si">}</span><span class="s2">&quot;</span> <span class="k">done</span> </pre></div> When designing a Core Data data model for your Xcode projects, you can choose to create Objective-C object wrappers for your entities, so that you can profit from type-safe code. The normal, tedious, workflow for this is that you select each entity from the model designer, select all of its attributes and relationships, Ctrl-click it and from the contextual menu first select “Copy Obj-C 2.0 Method Declarations To Clipboard”, paste it into the appropriate class header file, then do the same thing for the method implementations in the class implementation file. Waaaaaay too much work. Not to mention the manual copy-pastes are really hard to keep in sync once you start adding functionality to these class files, since you don’t want to overwrite those additions, but you want to keep replacing everything else. 2009-06-30T00:00:00+00:00 http://nvie.com/posts/nsmanagedobjectcontext-extensions/ NSManagedObjectContext extensions 2009-06-22T00:00:00+00:00 <p>The Core Data framework rules, and its API is really really powerful. But really, why does the Core Data API require us to write so much boilerplate code? Simple things need to be simple.</p> <p>Why is the deletion of a managed object from the NSManagedObjectContext so easy:</p> <div class="codehilite"><pre><span class="p">[</span><span class="n">context</span> <span class="nl">deleteObject</span><span class="p">:</span><span class="n">someObject</span><span class="p">];</span> </pre></div> <p>Compared to its creation:</p> <div class="codehilite"><pre><span class="p">[</span><span class="bp">NSEntityDescription</span> <span class="nl">insertNewObjectForEntityForName</span><span class="p">:</span><span class="s">@&quot;someObjectClassName&quot;</span> <span class="nl">inManagedObjectContext</span><span class="p">:</span><span class="n">context</span><span class="p">];</span> </pre></div> <h2 id="extending-nsmanagedobjectcontext">Extending NSManagedObjectContext <a href="#extending-nsmanagedobjectcontext" rel="bookmark" class="permalink">¶</a></h2> <p>Add the following category on NSManagedObjectContext to all of your Core Data projects and your pains will be history.</p> <div class="codehilite"><pre><span class="k">@implementation</span> <span class="bp">NSManagedObjectContext</span><span class="nl">(NSManagedObjectContextConvenienceMethods)</span> <span class="p">-</span> <span class="p">(</span><span class="kt">id</span><span class="p">)</span><span class="nf">newObject:</span><span class="p">(</span><span class="kt">Class</span><span class="p">)</span><span class="nv">entity</span> <span class="p">{</span> <span class="k">return</span> <span class="p">[</span><span class="bp">NSEntityDescription</span> <span class="nl">insertNewObjectForEntityForName</span><span class="p">:[</span><span class="n">entity</span> <span class="n">description</span><span class="p">]</span> <span class="nl">inManagedObjectContext</span><span class="p">:</span><span class="nb">self</span><span class="p">];</span> <span class="p">}</span> <span class="k">@end</span> </pre></div> <p>Now, a call to create a new object is as easy as deleting it.</p> <div class="codehilite"><pre><span class="p">[</span><span class="n">context</span> <span class="nl">newObject</span><span class="p">:[</span><span class="n">someEntity</span> <span class="k">class</span><span class="p">]];</span> </pre></div> <h2 id="further-enhancements-of-nsmanagedobject">Further enhancements of NSManagedObject <a href="#further-enhancements-of-nsmanagedobject" rel="bookmark" class="permalink">¶</a></h2> <p>Matt Gallagher has written an <a href="http://cocoawithlove.com/2008/03/core-data-one-line-fetch.html">excellent article</a> about how to further enhance NSManagedObject for adding simple, one-line fetch support. Be sure to check it out.</p> The Core Data framework rules, and its API is really really powerful. But really, why does the Core Data API require us to write so much boilerplate code? Simple things need to be simple. 2009-06-22T00:00:00+00:00 http://nvie.com/posts/nspredicateeditor-tutorial/ NSPredicateEditor tutorial 2009-06-20T00:00:00+00:00 <p>Cocoa offers a nice visual editor for editing NSPredicate objects templates, called NSPredicateEditor. The NSPredicateEditor can be set up using code or in Interface Builder, which is preferable for simple use. The setup is fairly easy once you know how to do it. In this tutorial, we’ll be building a simple predicate editor example which shows the basic functionality of the predicate editor.</p> <h2 id="setting-up-the-appdelegate">Setting up the AppDelegate <a href="#setting-up-the-appdelegate" rel="bookmark" class="permalink">¶</a></h2> <p>Begin by creating a new Xcode project (⌘⇧N). Name your project wisely and create a new class in the Classes group, called AppDelegate.</p> <p>Switch to the header file and declare two IBOutlets for the main window and the sheet on which we’re going to display the editor in a few minutes. Also, add two IBActions called <code>-openEditor:</code> and <code>-closeEditor:</code>. Finally, add an ivar that holds the NSPredicate we’re going to be editing.</p> <p><img alt="" src="/img/appdelegate1.png" /></p> <p>Next, we’re going to fire up Interface Builder to build the UI. Double click on the MainMenu.xib file under the Resources group.</p> <p>Drag an NSObject object from the Library into the XIB and call it App Delegate. Hit ⌘6 and make it a subclass of the AppDelegate class we just created. Then, hook it up to the delegate property of the File’s Owner.</p> <p><img alt="" src="/img/hookup-appdelegate.png" /> <img alt="" src="/img/choose-delegate.png" /></p> <p>Drag a new NSWindow to the XIB-file and call it Sheet. Make sure the checkbox “Visible At Launch” is deselected or the sheet will not display properly at runtime. Open the main window and add a NSButton and a NSTextView to it. To the sheet window, drag a NSPredicateEditor and a NSButton. They should look somewhat like this now:</p> <p><img alt="" src="/img/Picture-5.png" /> <img alt="" src="/img/Picture-4.png" /></p> <p>Now, we can hook up the outlets and actions as usual. Hook up the Edit Predicate button on the main window to <code>-openEditor:</code> and the OK button on the sheet window to closeEditor:. Then hook up the mainWindow and sheet outlets of the AppDelegate class to the respective NSWindow objects.</p> <p class="centered"><img alt="" src="/img/hookup-windows.png" /></p> <h2 id="configure-the-nspredicateeditor">Configure the NSPredicateEditor <a href="#configure-the-nspredicateeditor" rel="bookmark" class="permalink">¶</a></h2> <p>Once we have all of the connections between Xcode and Interface Builder set up, we can continue to configure the predicate editor itself, which is actually what this tutorial is all about. An NSPredicateEditor control uses a list of NSPredicateEditorRowTemplate objects that can handle individual (simple) NSPredicate objects. Combining these row templates enables the NSPredicateEditor to edit compound predicates. There is no limitation to the depth of nested compound predicates, although nesting too deep would not be advisable from a usability perspective.</p> <p>In the edit window, click a few times until the “name contains” row template is selected. In this row template, you define which key paths are supported. Supported here means two things:</p> <ul> <li><strong>matching</strong>—given an existing predicate with this key path in it on the left-hand side, this row template can be used to alter the predicate;</li> <li><strong>generation</strong>—when using the editor to create new predicates, adding a new rule for this key path will generate a predicate for this key path.</li> </ul> <p><img alt="" src="/img/Picture-10.png" /> <img alt="" src="/img/Picture-13.png" /></p> <h4 id="gotcha">Gotcha <a href="#gotcha" rel="bookmark" class="permalink">¶</a></h4> <p>A small gotcha, at least one that initially put me on the wrong foot, is that there is quite a difference between the rows that you see design-time in Interface Builder and the rows that are available run-time. At design-time, you define the NSPredicateEditorRowTemplate objects while at run-time you see instances of them. Hence, the number of rows at design-time is the <em>number of different row templates available</em>. At run-time, however, the number of rows is the number of <em>predicates within the compound predicate</em> (which each has an associated row template instance that handles it). Subtle difference.</p> <p>In short, in Interface Builder, <em>create a row template for <em>each type of match</em> that you want to allow</em>. Typically, this means for each data type that you want to support. In our example, we have the following setup:</p> <ul> <li>Row template #1 is for all string matches. Here, we have defined it for the key paths “firstname”, “lastname”, “address.street” and “address.city”. They, per definition, have the same allowed operators. If we want to have an other set of operators for a specific key path, we need to define a separate row template for it.</li> <li>Row template #2 is for date matches, i.e. our “birthdate” key path.</li> <li>Row template #3 is for all integer matches, i.e. our “address.number” key path.</li> </ul> <p>The result looks like this:</p> <p class="centered"><img alt="" src="/img/row-templates-setup.png" /></p> <h2 id="using-bindings-to-connect-the-predicate-to-the-ui">Using bindings to connect the predicate to the UI <a href="#using-bindings-to-connect-the-predicate-to-the-ui" rel="bookmark" class="permalink">¶</a></h2> <p><img alt="" class="right" src="/img/bindings.png" /></p> <p>Next up, we simply connect both the text view from the main window and the predicate editor from the sheet window to the predicate key path using Cocoa bindings. In order to do so, select the NSPredicateEditor (first click the control to select the scroll view, then click again to select the inner NSPredicateEditor), hit ⌘4. Then, unfold the “Value” binding and hook it up to the App Delegate’s “predicate” key path.</p> <p>Do the same for the text view in the main window, but this time hook it up to the “predicate.description” key path (since only strings can be displayed in a text view). When you do this, make sure that the text view is read-only, since the description property of objects should never be set.</p> <h2 id="writing-the-code-to-wrap-it-all-up">Writing the code to wrap it all up <a href="#writing-the-code-to-wrap-it-all-up" rel="bookmark" class="permalink">¶</a></h2> <p>Finally, we have only a bit of code to write in our AppDelegate implementation, so let’s go:</p> <div class="codehilite"><pre><span class="c1">//</span> <span class="c1">// AppDelegate.m</span> <span class="c1">// PredicateEditorTest</span> <span class="c1">//</span> <span class="c1">// Created by Vincent on 20-07-09.</span> <span class="c1">//</span> <span class="cp">#import &quot;AppDelegate.h&quot;</span> <span class="cp">#define DEFAULT_PREDICATE @&quot;(firstname = &#39;John&#39; AND lastname = &#39;Doe&#39;) &quot; </span> <span class="s">@&quot;OR birthdate &gt; CAST(&#39;01/01/1985&#39;, &#39;NSDate&#39;) &quot;</span> <span class="s">@&quot;OR address.city = &#39;Chicago&#39; &quot;</span> <span class="s">@&quot;AND address.street != &#39;Main Street&#39; &quot;</span> <span class="s">@&quot;OR address.number &gt; 1000&quot;</span> <span class="k">@implementation</span> <span class="nc">AppDelegate</span> <span class="p">-</span> <span class="p">(</span><span class="kt">id</span><span class="p">)</span><span class="nf">init</span> <span class="p">{</span> <span class="nb">self</span> <span class="o">=</span> <span class="p">[</span><span class="nb">super</span> <span class="n">init</span><span class="p">];</span> <span class="k">if</span> <span class="p">(</span><span class="nb">self</span> <span class="o">!=</span> <span class="nb">nil</span><span class="p">)</span> <span class="p">{</span> <span class="n">predicate</span> <span class="o">=</span> <span class="p">[[</span><span class="bp">NSPredicate</span> <span class="nl">predicateWithFormat</span><span class="p">:</span><span class="n">DEFAULT_PREDICATE</span><span class="p">]</span> <span class="k">retain</span><span class="p">];</span> <span class="p">}</span> <span class="k">return</span> <span class="nb">self</span><span class="p">;</span> <span class="p">}</span> <span class="p">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf">dealloc</span> <span class="p">{</span> <span class="p">[</span><span class="n">predicate</span> <span class="k">release</span><span class="p">];</span> <span class="p">[</span><span class="nb">super</span> <span class="n">dealloc</span><span class="p">];</span> <span class="p">}</span> <span class="p">-</span> <span class="p">(</span><span class="kt">IBAction</span><span class="p">)</span><span class="nf">openEditor:</span><span class="p">(</span><span class="kt">id</span><span class="p">)</span><span class="nv">sender</span> <span class="p">{</span> <span class="p">[</span><span class="n">NSApp</span> <span class="nl">beginSheet</span><span class="p">:</span><span class="n">sheet</span> <span class="nl">modalForWindow</span><span class="p">:</span><span class="n">mainWindow</span> <span class="nl">modalDelegate</span><span class="p">:</span><span class="nb">nil</span> <span class="nl">didEndSelector</span><span class="p">:</span><span class="nb">NULL</span> <span class="nl">contextInfo</span><span class="p">:</span><span class="nb">nil</span><span class="p">];</span> <span class="p">}</span> <span class="p">-</span> <span class="p">(</span><span class="kt">IBAction</span><span class="p">)</span><span class="nf">closeEditor:</span><span class="p">(</span><span class="kt">id</span><span class="p">)</span><span class="nv">sender</span> <span class="p">{</span> <span class="p">[</span><span class="n">NSApp</span> <span class="nl">endSheet</span><span class="p">:</span><span class="n">sheet</span><span class="p">];</span> <span class="p">[</span><span class="n">sheet</span> <span class="nl">orderOut</span><span class="p">:</span><span class="n">sender</span><span class="p">];</span> <span class="p">}</span> <span class="k">@end</span> </pre></div> <p>In the <code>-init:</code> method, we initialize the AppDelegate by setting and retaining a reference to a rather complex default predicate. When the XIB is loaded at run-time, the textbox shows exactly this predicate and it can be edited by invoking the edit sheet.</p> <p>The actual implementation of the <code>-openEditor:</code> and <code>-closeEditor:</code> methods aren’t too exciting.</p> <h2 id="downloading-the-source">Downloading the source <a href="#downloading-the-source" rel="bookmark" class="permalink">¶</a></h2> <p>You can download the source code for this tutorial as an Xcode project here.</p> <p class="centered"><a href="/files/PredicateEditorTest.zip"><img alt="" src="/img/zip@2x.png" style="max-width: 128px" /></a><br /> <a href="/files/PredicateEditorTest.zip">PredicateEditorTest.zip</a></p> <p>Have a blast!</p> Cocoa offers a nice visual editor for editing NSPredicate objects templates, called NSPredicateEditor. The NSPredicateEditor can be set up using code or in Interface Builder, which is preferable for simple use. The setup is fairly easy once you know how to do it. In this tutorial, we’ll be building a simple predicate editor example which shows the basic functionality of the predicate editor. 2009-06-20T00:00:00+00:00