一下是nltk decorator.py的部分代码。70 行是原来的代码,我运行时说是由于版本问题,进行了修改。不知会不会造成新的问题。现在问题出现在80行, 运行时出现了 UnboundLocalError: cannot access local variable 'signature' where it is not associated with a value。 作为常用的一个nltk程序,怎么会出现这样的问题呢?
Decorator module by Michele Simionato <michelesimionato@libero.it>
Copyright Michele Simionato, distributed under the terms of the BSD License (see below).
http://www.phyast.pitt.edu/~micheles/python/documentation.html
Included in NLTK for its support of a nice memoization decorator.
"""
from __future__ import print_function
__docformat__ = 'restructuredtext en'
## The basic trick is to generate the source code for the decorated function
## with the right signature and to evaluate it.
## Uncomment the statement 'print >> sys.stderr, func_src' in _decorator
## to understand what is going on.
__all__ = ["decorator", "new_wrapper", "getinfo"]
import sys
# Hack to keep NLTK's "tokenize" module from colliding with the "tokenize" in
# the Python standard library.
old_sys_path = sys.path[:]
sys.path = [p for p in sys.path if "nltk" not in p]
import inspect
sys.path = old_sys_path
try:
set
except NameError:
from sets import Set as set
def getinfo(func):
"""
Returns an info dictionary containing:
- name (the name of the function : str)
- argnames (the names of the arguments : list)
- defaults (the values of the default arguments : tuple)
- signature (the signature : str)
- doc (the docstring : str)
- module (the module name : str)
- dict (the function __dict__ : str)
>>> def f(self, x=1, y=2, *args, **kw): pass
>>> info = getinfo(f)
>>> info["name"]
'f'
>>> info["argnames"]
['self', 'x', 'y', 'args', 'kw']
>>> info["defaults"]
(1, 2)
>>> info["signature"]
'self, x, y, *args, **kw'
"""
assert inspect.ismethod(func) or inspect.isfunction(func)
if sys.version_info[0] >= 3:
argspec = inspect.getfullargspec(func)
else:
argspec = inspect.getargspec(func)
regargs, varargs, varkwargs, defaults = argspec[:4]
argnames = list(regargs)
if varargs:
argnames.append(varargs)
if varkwargs:
argnames.append(varkwargs)
signature = inspect.signature(inspect.formatargspec(regargs, varargs, varkwargs, defaults, formatvalue=lambda value: "")[1:-1])
#signature = inspect.formatargspec(regargs, varargs, varkwargs, defaults, formatvalue=lambda value: "")[1:-1]
# pypy compatibility
if hasattr(func, '__closure__'):
_closure = func.__closure__
_globals = func.__globals__
else:
_closure = func.func_closure
_globals = func.func_globals
return dict(name=func.__name__, argnames=argnames, signature=signature,
defaults = func.__defaults__, doc=func.__doc__,
module=func.__module__, dict=func.__dict__,
globals=_globals, closure=_closure)