Skip to content

Register import hook instead of directly wrapping when module is string #275

@anuraaga

Description

@anuraaga

Currently, wrapping via e.g. wrap_function_wrapper import wrapped modules right away

https://github.com/GrahamDumpleton/wrapt/blob/develop/src/wrapt/patches.py#L17

I was wondering if it could make sense to instead register a import hook using register_import_hook. Conceptually,

Before

wrap_function_wrapper(module, ...):
  if isinstance(module, str):
    module = import(module)
  do_stuff_with_module(module, ...)

After

wrap_function_wrapper(module, ...):
  if isinstance(module, str):
    register_import_hook(module, do_stuff_with_module)
    return
  do_stuff_with_module(module, ...)

I understand this would be a big difference in behavior but I wonder if there is any conceivable case where it could affect downstream code. Currently, calls to wrap_ eagerly import the libraries, which means loading libraries to monkey patch which may not actually be imported by the application. Instead using an import hook would allow monkey patching only when a library is actually used which could have some memory benefits, etc. If a user passed a module in directly it would still behave as currently - a string for module seems like a good user intent to want "lazy behavior".

It's not difficult to expect callers to use the import hook themselves so it's not a big deal, just wanted to bring up the idea in case it could make it easier for wrappers without causing regressions in behavior. Just for reference, this would make the behavior match closer e.g. nodejs/import-in-themiddle or Java classloader instrumentation in agents - I doubt that should be a priority for this library but just for context.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions