title: Checking if an object is in a repo in gitpython
body: <p>I'm working on a program that will be adding and updating files in a git repo. Since I can't be sure if a file that I am working with is currently in the repo, I need to check its existence - an action that seems to be harder than I thought it would be. </p>
  
  <p>The 'in' comparison doesn't seem to work on non-root levels on trees in gitpython. Ex.</p>
  
  <pre><code>&gt;&gt;&gt; repo = Repo(path)
  &gt;&gt;&gt; hct = repo.head.commit.tree
  &gt;&gt;&gt;&gt; 'A' in hct['documents']
  False
  &gt;&gt;&gt; hct['documents']['A']
  &lt;git.Tree "8c74cba527a814a3700a96d8b168715684013857"&gt;
  </code></pre>
  
  <p>So I'm left to wonder, how do people check that a given file is in a git tree before trying to work on it? Trying to access an object for a file that is not in the tree will throw a KeyError, so I can do try-catches. But that feels like a poor use of exception handling for a routine existence check.</p>
  
  <p>Have I missed something really obvious? How does once check for the existence of a file in a commit tree using gitpython (or really any library/method in Python)?</p>
  
  <p><strong>Self Answer</strong></p>
  
  <p>OK, I dug around in the <a href="https://github.com/gitpython-developers/GitPython/blob/master/git/objects/tree.py" rel="nofollow">Tree class</a> to see what __contains__ does. Turns out, when searching in sub folders, one has to check for existence of a file using the full relative path from the repo's root. So a working version of the check I did above is:</p>
  
  <pre><code>&gt;&gt;&gt; 'documents/A' in hct['documents']
  True
  </code></pre>