2

Possible Duplicate:
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, 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
Community
  • 1
  • 1
kirakun
  • 2,770
  • 1
  • 25
  • 41

1 Answers1

3

You can use the 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).

BrenBarn
  • 242,874
  • 37
  • 412
  • 384