如何从 Python shell 调用内部函数?

发布于 2024-09-20 00:12:42 字数 259 浏览 9 评论 0原文

我有一些代码(我无法轻易修改),其形式如下:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岛徒 2024-09-27 00:12:42

正如您所说的那样,不可能使用代码获取内部函数对象 - 仅当外部函数时才创建该对象(通过 def 语句) 运行(即,当它被调用时)。

顺便说一句,请注意,像 foo 这样的外部函数通常被编码为返回内部函数作为结果(例如,通过将 bar() 更改为return bar) 作为最后一行,完全作为“函数工厂”(通常作为“闭包工厂”)工作,而不是将内部函数的存在保留为一种私有的、秘密的实现细节;但您的编码选择了后一条路线。

编辑...:

可以获取内部函数的代码对象,但是:

>>> def outer():
...   def inner(): return 'boo'
...   print inner()
... 
>>> eval(outer.func_code.co_consts[1])
'boo'
>>> 

但是,一般来说,要制作一个将代码对象转换为可调用函数需要大量工作(在这种特殊情况下,一个 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 changing bar() to return 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:

>>> def outer():
...   def inner(): return 'boo'
...   print inner()
... 
>>> eval(outer.func_code.co_consts[1])
'boo'
>>> 

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文