Text of a Python Function
Question: > **Possible Duplicate:**  
>  [How can I get the source code of a Python
> function?](http://stackoverflow.com/questions/427453/how-can-i-get-the-
> source-code-of-a-python-function)

First, let me define my problem. I will give a motivation afterward.

## Problem:

    
    
    def map(doc):
      yield doc['type'], 1
    
    # How do I get the textual representation of the function map above,
    # as in getting the string "def map(doc):\n  yield doc['yield'], 1"?
    print repr(map)  # Does not work. It prints <function fun at 0x10049c8c0> instead.
    

## Motivation:

For those of you familiar with CouchDB views, I am writing a Python script to
generate CouchDB views, which are JSON with the map and reduce functions
embedded. For example,

    
    
    {
      "language": "python",
      "views": {
        "pytest": {
          "map": "def fun(doc):\n  yield doc['type'], 1",
          "reduce": "def fun(key, values, rereduce):\n  return sum(values)"
        }
      }
    }
    

However, for readability, I would prefer to write the `map` and `reduce`
function natively in the Python script first, then construct the above JSON
using the answer to this question.

## Solution:

By [BrenBarn's response](http://stackoverflow.com/a/12452106/560074), use
`inspect.getsource`.

    
    
    #!/usr/bin/env python
    
    import inspect
    
    def map(doc):
      yield doc['type'], 1
    
    def reduce(key, values, rereduce):
      return sum(values)
    
    couchdb_views = {
      "language": "python",
      "views": {
         "pytest": {
           "map": inspect.getsource(map),
           "reduce": inspect.getsource(reduce),
         }
      }
    }
    
    # Yay!
    print couchdb_views
    


Answer: You can use the
[`inspect.getsource`](http://docs.python.org/library/inspect.html#inspect.getsource)
function to get the source of a function. Note that for this to work the
function has to be loaded from a file (e.g., it won't work for functions
defined in the interactive interpreter).

