Python: Check for write only attr of a Class

时间:2017-03-06 09:29:51

标签: python

I'm using a Class provided by a client (I have no access to the object code), and I'm trying to check if a object has a attribute. The attribute itself is write only, so the hasattr fails:

>>> driver.console.con.input = 'm'
>>> hasattr(driver.console.con, 'input')
False
>>> simics> @driver.console.con.input
Traceback (most recent call last):
File "<string>", line 1, in <module>
Attribute: Failed converting 'input' attribute in object   
'driver.console.con' to Python: input attribute in driver.console.con 
object: not readable.

Is there a different way to check if an attribute exists?

1 个答案:

答案 0 :(得分:3)

您似乎拥有某种将Python连接到扩展的本机代码代理,而且它违反了正常的Python惯例

有两种可能性:

  1. driver.console.con对象有一个名称空间,它将属性实现为descriptors,而input描述符只有__set__ method(可能还有__delete__ method })。在这种情况下,查找描述符:

    if 'input' in vars(type(driver.console.con)):
        # there is an `input` name in the namespace
        attr = vars(type(driver.console.con))['input']
        if hasattr(attr, '__set__'):
            # can be set
            ...
    

    此处vars() function检索用于driver.console.con的命名空间。

  2. 代理使用__getattr__(甚至__getattribute__)和__setattr__ hooks来处理任意属性。你在这里运气不好,你无法检测任何方法在hasattr()之外支持哪些属性并尝试直接设置属性。使用try...except保护:

    try:
        driver.console.con.input = 'something'
    except Attribute:   # exactly what exception object does this throw?
        # can't be set, not a writable attribute
        pass
    

    您可能必须使用调试器或print()语句来确切地确定抛出的异常(使用try...except Exception as ex:块来捕获所有异常,然后检查ex);在你的问题的追溯中,最后的异常消息看起来非常不标准。那个项目真的应该提高AttributeError

  3. 考虑到抛出相当自定义的异常,我的钱在选项2上(但如果描述符上的__get__方法抛出异常,则选项1仍然存在)。