我认为测试用例可能会导致误报。您是否有可能在调用之前忘记del
了变量?xyz
fun()
定义一个函数会在当前范围内创建一个局部变量,该变量引用该函数对象。例如:
def fun():
x = X()
创建由当前范围内function
的变量引用的对象。fun
如果调用该函数,则(默认情况下)创建一个新的本地范围,其中返回的对象将在函数的本地范围内X()
引用,而不是在调用者的框架内。x
locals()
这是一个基于原始代码的示例:
#include <boost/python.hpp>
/// @brief Mockup types.
struct X
{
X()
{
// Borrow a reference from the locals dictionary to create a handle.
// If PyEval_GetLocals() returns NULL, then Boost.Python will throw.
namespace python = boost::python;
python::object locals(python::borrowed(PyEval_GetLocals()));
// Inject a reference to the int(42) object as 'xyz' into the
// frame's local variables.
locals["xyz"] = 42;
}
};
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
python::class_<X>("X", python::init<>());
}
断言可见性的交互式使用:
>>> import example
>>> def fun():
... assert('xyz' not in locals())
... x = example.X()
... assert('xyz' in locals())
... assert('xyz' not in globals())
...
>>> assert('xyz' not in globals())
>>> fun()
>>> assert('xyz' not in globals())
>>> x = example.X()
>>> assert('xyz' in globals())
>>> del xyz
>>> fun()
>>> assert('xyz' not in globals())
为了完整起见,可以使用未设置标志的aFuncionType
来构造 a ,从而导致用于函数调用的帧的返回值与. 这是一个交互式使用示例,演示了这一点:CodeType
co_flags
newlocals
locals()
globals()
>>> def fun():
... x = 42
... print "local id in fun:", id(locals())
...
>>> import types
>>> def no_locals(fn):
... func_code = fn.func_code
... return types.FunctionType(
... types.CodeType(
... func_code.co_argcount,
... func_code.co_nlocals,
... func_code.co_stacksize,
... func_code.co_flags & ~2, # disable newlocals
... func_code.co_code,
... func_code.co_consts,
... func_code.co_names,
... func_code.co_varnames,
... func_code.co_filename,
... func_code.co_name,
... func_code.co_firstlineno,
... func_code.co_lnotab),
... globals())
...
>>> id(globals())
3075430164L
>>> assert('x' not in locals())
>>> fun()
local id in fun: 3074819588
>>> assert('x' not in locals())
>>> fun = no_locals(fun) # disable newlocals flag for fun
>>> assert('x' not in locals())
>>> fun()
local id in fun: 3075430164
>>> assert('x' in locals())
>>> x
42
即使在禁用newlocals
标志之后,我也必须调用 insidelocals()
来fun()
观察x
被插入到全局符号表中。