How to fake/proxy a class in Python

前端 未结 3 645
花落未央
花落未央 2020-11-29 07:17

I wrote some wrapper which has another object as an attribute. This wrapper proxies (forwards) all attribute requests with __getattr__ and __setattr__

3条回答
  •  醉酒成梦
    2020-11-29 07:56

    Generally, you can use the wrapt library (pypi), which does the heavy lifting for you:

    The wrapt module focuses very much on correctness. It therefore goes way beyond existing mechanisms such as functools.wraps() to ensure that decorators preserve introspectability, signatures, type checking abilities etc. [...]

    To ensure that the overhead is as minimal as possible, a C extension module is used for performance critical components

    It supports creating custom wrapper classes. In order to add your own attributes, you need to declare them in such a way that wrapt doesn't try to pass them on to the wrapped instance. You can:

    • Prefix the attribute with _self_ and add properties for access
    • Declare the attribute at the class level, in addition to in __init__
    • Use slots, if appropriate for your class (not mentioned in the docs), like this:

      class ExtendedMesh(ObjectProxy):
          __slots__ = ('foo')
      
          def __init__(self, subject):
              super().__init__(subject)
              self.foo = "bar"
      

    It also supports function wrappers, which might suit your purpose.

提交回复
热议问题