我开始将一些代码从Python2.x移植到Python3.x,但在我开始之前,我想把它升级到最近的2.7。我在使用各种工具(例如futurize)方面取得了很好的进展,但他们留下的一个领域就是buffer()的使用。在Python3.x中,buffer()已经被移除,取而代之的是memoryview(),它通常看起来更干净,但它不是一对一的交换。
它们的一个不同之处在于:
In [1]: a = "abcdef"
In [2]: b = buffer(a)
In [3]: m = memoryview(a)
In [4]: print b, m
abcdef <memory at 0x101b600e8>也就是说,str(<buffer object>)返回一个包含对象内容的字节字符串,而memoryviews返回它们的repr()。我认为新的行为更好,但它也带来了问题。
特别是,我有一些代码抛出了一个异常,因为它正在接收一个包含<memory at 0x1016c95a8>的字节字符串。这表明在其他地方有一段代码依赖于这种行为来工作,但我真的很难找到它。
对于这类问题,有没有人有很好的调试技巧?
发布于 2014-02-03 04:30:45
一种可能的技巧是编写memoryview的子类,并将所有memoryview实例临时更改为memoryview_debug版本:
class memoryview_debug(memoryview):
def __init__(self, string):
memoryview.__init__(self, string)
def __str__(self):
# ... place a breakpoint, log the call, print stack trace, etc.
return memoryview.__str__(self)编辑:
正如OP所指出的,显然不可能从memoryview继承子类。幸运的是,多亏了动态类型,这在Python中并不是一个大问题,它将变得更加不方便。您可以将继承更改为组合:
class memoryview_debug:
def __init__(self, string):
self.innerMemoryView = memoryview(string)
def tobytes(self):
return self.innerMemoryView.tobytes()
def tolist(self):
return self.innerMemoryView.tolist()
# some other methods if used by your code
# and if overridden in memoryview implementation (e.g. __len__?)
def __str__(self):
# ... place a breakpoint, log the call, print stack trace, etc.
return self.innerMemoryview.__str__()https://stackoverflow.com/questions/21515729
复制相似问题