可能重复:
如何获取 Python 函数的源代码?
首先,让我定义我的问题。之后我会给一个动力。
问题:
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.
动机:
对于那些熟悉 CouchDB 视图的人,我正在编写一个 Python 脚本来生成 CouchDB 视图,这些视图是嵌入了 map 和 reduce 函数的 JSON。例如,
{
"language": "python",
"views": {
"pytest": {
"map": "def fun(doc):\n yield doc['type'], 1",
"reduce": "def fun(key, values, rereduce):\n return sum(values)"
}
}
}
但是,为了可读性,我更愿意先在 Python 脚本中本地编写map
andreduce
函数,然后使用此问题的答案构造上述 JSON。
解决方案:
根据BrenBarn 的回应,使用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