如何避免在Python中覆盖系统库的属性?

时间:2013-03-18 16:47:04

标签: python python-module

假设我们有一段错误的代码,意外地覆盖了某些系统库的属性,如下所示:

import socket
socket.error = 'some other object'

有没有办法阻止这种行为,或找到负责这样做的代码?

我尝试用socket.error创建一个属性,但这不起作用:

def fget(self):
    return socket.error

def fset(self, value):
    raise SystemError('You cannot alter this attribute.')

# From now on, settings socket.error = x should raise an error
socket.error = property(fget, fset)

1 个答案:

答案 0 :(得分:6)

您可以(暂时)将其粘贴在您的代码中:

class Bridge(object):
    def __init__(self, module):
        self.__dict__['module'] = module
    def __getattr__(self, attr):
        return getattr(self.module, attr)
    def __setattr__(self, attr, val):
        raise TypeError('{a!r} can not be set'.format(a=attr))

import sys
import socket
socket = sys.modules['socket'] = Bridge(socket)

然后在socket上设置属性(至少以最常见的方式)会引发异常。回溯将允许您找到错误。

print(socket.error)
setattr(socket, 'error', 'blah')

产量

% test.py
<class 'socket.error'>
Traceback (most recent call last):
  File "/home/unutbu/pybin/test.py", line 15, in <module>
    setattr(socket, 'error', 'blah')
  File "/home/unutbu/pybin/test.py", line 10, in __setattr__
    raise TypeError('{a!r} can not be set'.format(a=attr))
TypeError: 'error' can not be set