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
2
  • Doesn't CouchDB want javascript map / reduce functions? Commented Sep 17, 2012 at 4:57
  • @dokkaebi CouchDB may have map/reduce/ddoc functions in any languages if only you have setup query server for their support. Commented Sep 17, 2012 at 5:52

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.