应用d时模块导入失败

2024-09-30 22:20:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模块,我作为一个装饰-修改我递归使用的函数

该模块优化了tail call以避免递归限制-参见下面的credits

如果我在控制台上复制粘贴代码,首先是模块,然后是修饰的函数,就可以了

但是如果我导入模块,我会得到一个错误,模块无法导入sys-尽管我在模块的第一行导入了它

    Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "TailRecurseException.py", line 18, in func
    f = sys._getframe()
NameError: global name 'sys' is not defined
>>> 

我以为导入模块的方式不对:

我试过了

from TailRecurseException import tail_call_optimized

以及

from TailRecurseException import *

@tail_call_optimized
def recursive_activations( ...)

但同样的结果

我可以在模块中做什么错误来装饰另一个函数,因为它无法导入sys


这是我的子模块:

import sys


class TailRecurseException:
  def __init__(self, args, kwargs):
    self.args = args
    self.kwargs = kwargs


def tail_call_optimized(g):
  """
  This function decorates a function with tail call
  optimization. It does this by throwing an exception
  if it is it's own grandparent, and catching such
  exceptions to fake the tail call optimization.

  This function fails if the decorated
  function recurses in a non-tail context.
  """
  def func(*args, **kwargs):
    f = sys._getframe()
    if f.f_back and f.f_back.f_back \
        and f.f_back.f_back.f_code == f.f_code:
      raise TailRecurseException(args, kwargs)
    else:
      while 1:
        try:
          return g(*args, **kwargs)
        except TailRecurseException, e:
          args = e.args
          kwargs = e.kwargs
  func.__doc__ = g.__doc__
  return func

学分:https://mail.python.org/pipermail//python-list/2006-February/407243.html


Tags: 模块函数inimportdefsysbackargs
1条回答
网友
1楼 · 发布于 2024-09-30 22:20:00

如果我复制粘贴您附加到tcr.py的子模块代码,那么

from tcr import tail_call_optimized

@tail_call_optimized
def recursive_activations(x):
    pass

一切正常

(另一方面,您需要将except TailRecurseException, e:更改为except TailRecurseException as e:,以符合现代Python的要求。)

相关问题 更多 >