我认为测试用例可能会导致误报。在调用 fun() 之前,您是否可能忘记了 del xyz 变量?
定义一个函数会在当前范围内创建一个局部变量,该变量引用该函数对象。例如:
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())
为了完整起见,CodeType 可以使用 co_flags 未设置 newlocals 标志的 CodeType 构造,从而导致用于函数调用的框架使其 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 标志之后,我也必须在 fun() 中调用 locals() 才能观察到 x 被插入到全局符号表中。