如何从 Python shell 调用内部函数?
我有一些代码(我无法轻易修改),其形式如下:
def foo(x):
do_other_stuff_that_I_do_not_want_to_do()
def bar():
"do something"
str(x)
bar()
我想直接从 Python shell 调用 bar()
。我不介意使用 co_globals 或其他内部位。我感觉这可能是不可能的;是吗?
I have some code (that I can't easily modify), of the following form:
def foo(x):
do_other_stuff_that_I_do_not_want_to_do()
def bar():
"do something"
str(x)
bar()
I would like to call bar()
, directly, from the Python shell. I don't mind using co_globals
, or other internal bits. I have the feeling that this may be impossible; is it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如您所说的那样,不可能使用代码获取内部函数对象 - 仅当外部函数时才创建该对象(通过
def
语句) 运行(即,当它被调用时)。顺便说一句,请注意,像
foo
这样的外部函数通常被编码为返回内部函数作为结果(例如,通过将bar()
更改为return bar
) 作为最后一行,完全作为“函数工厂”(通常作为“闭包工厂”)工作,而不是将内部函数的存在保留为一种私有的、秘密的实现细节;但您的编码选择了后一条路线。编辑...:
可以获取内部函数的代码对象,但是:
但是,一般来说,要制作一个将代码对象转换为可调用函数需要大量工作(在这种特殊情况下,一个
eval
就足够了,因为内部函数没有参数,也没有任何非局部变量,但当然,这不是任何地方,甚至接近一般情况...您必须提供非本地绑定等细节!-)It is impossible to get at the inner function object with the code as you've stated it -- said object is only created (by the
def
statement) when the outer function runs (i.e., when it gets called).As an aside, note that outer functions like
foo
are often coded to return the inner function as their result (e.g. by changingbar()
toreturn bar
) as the last line, exactly to work as "function factories" (often, as "closure factories") rather than keep the very existence of an internal function as a kind of private, secret implementation detail; but your coding picks the latter route instead.Edit...:
It is possible to get at the code object for the inner function, however:
However, in general, to make a code object into a callable function requires considerable work (in this special case an
eval
suffices because the inner function has no arguments nor any nonlocal variables, but of course that's not anywhere even close to the general case... in which you do have to supply such niceties as bindings for nonlocals!-)