by btown · 7y ago · 0 comments
Python is scary sometimes. If it looks like a duck and quacks like a duck and isinstance(duck), it might be an alien masquerading as a duck using metaclasses to accomplish these feats. But with this craziness comes the ability to make a transparent runtime proxy to just about anything in Python, and do so recursively e.g. to track all uses of an object hierarchy.
Definitely agree about metaclass magic being a blessing and a curse. That superdelegate library was fun to write and uses a metaclass to make the API pleasant.
For instance, I've seen instrumentation libraries monkey-patch database cursors with wrappers around those cursors, so the library can detect usage of the cursor without changing its behavior.
Django itself has a LazyObject class, which operates similarly to an ObjectProxy but only evaluates its wrapped initializer when one of its properties is accessed: https://docs.djangoproject.com/en/2.2/_modules/django/utils/...
And I'm using wrapt in a project (which I hope to open source) where, by recursively wrapping the return value of every __getitem__ and __getattr__ with a properly-bookkept proxy object, you can see what subgraph of a complicated object hierarchy was actually used by a function call (say, the rendering of a Django or Jinja template). Possibilities of such a transformation are endless!
http://docs.groovy-lang.org/2.4.9/html/gapi/groovy/lang/Dele...