astroid icon indicating copy to clipboard operation
astroid copied to clipboard

Ability to overwrite transforms or improved support for unregistering transforms

Open ltcmelo opened this issue 5 years ago • 2 comments

I need to write a (module) transform for a a module that is already part of astroid's brain — think of my transform as an extension/enhancement of the transform existing one.

Problems:

  • unregister_transform requires both the transform itself and (possibly) a predicate; however, obtaining those 2 may not be possible… for instance, they're aren't exposed in the builtin brain.

  • calling register_transform "again" isn't a solution, given that this function doesn't overwrite a previously registered transform, it only appends thew new transform to a list; therefore, the one that matches first will be applied.

The way I'm working around this situation so far is like this:

    class Mock:
        def __init__(self, name):
            self.name = name

    mock = Mock('hashlib')

    for node_type, data in manager._transform.transforms.items():
        if node_type == nodes.Module:
            for transform, pred in data:
                if pred(mock):
                    manager.unregister_transform(node_type, transform, pred)

In this example ☝️ I'm unregistered the transform for hashlib by iterating over (intendedly) private field that contains the transforms container and testing whether or not the predicate matches. Not ideal…

Am I missing anything or there's indeed a need for an API here?

ltcmelo avatar Aug 25 '20 14:08 ltcmelo

This is similar to https://github.com/PyCQA/astroid/issues/816.

I also have not found a public API for that.

eugene57 avatar Sep 15 '20 21:09 eugene57

Thanks, this was a good report. We definitely need to look over the API for this.

PCManticore avatar Dec 26 '20 17:12 PCManticore