title: Getting the line number of the definition of a function
body: <p>I'd like to get the file path and line number of the definition of a given function (or method). I can use <code>inspect.getfile</code> for the path, but <code>inspect.getlineno</code> takes a frame, and that's where I get stuck.</p>
  <p>I could probably get to my goal with something like this (that gives me the byte offset instead of the line number), but I can't help but think that there's a better way.</p>
  <pre class="lang-py prettyprint-override"><code>import re
  import inspect
  
  
  def src_path_and_line_number(f):
      src_filepath = inspect.getfile(f)
      module = inspect.getmodule(f)
      module_src = inspect.getsource(module)
      f_src = inspect.getsource(f)
      m = re.search(re.escape(f_src), module_src, re.MULTILINE)
      if m:
          return src_filepath, m.start()
  </code></pre>
  <p>Example:</p>
  <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; from pathlib import PosixPath
  &gt;&gt;&gt; src_path_and_line_number(PosixPath)
  ('.../.pyenv/versions/3.8.6/lib/python3.8/pathlib.py', 51265)
  &gt;&gt;&gt; src_path_and_line_number(PosixPath.glob)
  ('.../.pyenv/versions/3.8.6/lib/python3.8/pathlib.py', 37864)
  </code></pre>
  <p><em>Note:
  I know in some cases it won't work -- in fact, <code>inspect.getfile</code> doesn't always work either. But it's okay. Just as <code>inspect.getfile</code> is still useful, so would my linenumber information be useful when it is possible to get.</em></p>