Search code examples
pythonmonkeypatching

How can I check if I can set (patch) attributes in Python objects


Setting arbitrary attributes from outside works for normal classes, but not for internal objects like strings?! How can I check if I'm allowed to set arbitrary attributes?


Solution

  • Use try-except

    def canSetAttr(o):
        try:
             name = 'probablynotset'
             flag = hasattr(o, name)
             if flag:
                 old = getattr(o, name)
             setattr(o, name, 'x')
             if flag:
                 setattr(o, name, old)
             else:
                 delattr(o, name)
    
             return True
         except AttributeError:
             return False