gpt4 book ai didi

python - Python 函数的文本

转载 作者:太空宇宙 更新时间:2023-11-04 01:32:58 24 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
How can I get the source code of a Python function?

首先,让我定义一下我的问题。之后我会给出一个动机。

问题:

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 View 的人,我正在编写一个 Python 脚本来生成 CouchDB View ,这些 View 是嵌入了 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 脚本中本地编写 mapreduce 函数,然后使用这个问题的答案构造上面的 JSON .

解决方案:

通过 BrenBarn's response , 使用 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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com