Skip to content

Plugin hook to customize __repr__ of an Instance #6501

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
mkurnikov opened this issue Mar 1, 2019 · 1 comment
Open

Plugin hook to customize __repr__ of an Instance #6501

mkurnikov opened this issue Mar 1, 2019 · 1 comment
Labels
feature priority-1-normal topic-plugins The plugin API and ideas for new plugins

Comments

@mkurnikov
Copy link
Contributor

mkurnikov commented Mar 1, 2019

For example, in Django, there's this QuerySet object with a lot of methods, and to properly support those methods we need two (and maybe more in the future) generic parameters.

With get_type_analyze_hook I can convert QuerySet[MyModel] into QuerySet[MyModel, MyModel], so in the code user don't need to think about number of generics. But in error messages, all those generics values are present, though they don't have any semantics, it's just implementation detail.

Or, for Field, I need to have two generic params, one for type of __set__, one for __get__, so they appear in error message as (CharField for example)

django.db.models.fields.CharField[Union[builtins.str, builtins.int, django.db.models.expressions.Combinable], builtins.str]

None of this info makes any sense to users, so I want it to just be django.db.models.fields.CharField.

This is monkeypatching version that works for one of the cases, should be simple enough to add hook for that,

def make_queryset_repr_return_only_one_type():
    from mypy.types import TypeStrVisitor

    old_visit_instance = TypeStrVisitor.visit_instance

    def patched_visit_instance(self, t: Instance) -> str:
        if t.type.has_base(helpers.QUERYSET_CLASS_FULLNAME):
            return old_visit_instance(self, helpers.reparametrize_instance(t, [t.args[0]]))
        else:
            return old_visit_instance(self, t)

    TypeStrVisitor.visit_instance = patched_visit_instance

I can make a PR, if you approve it as a viable feature.

@ilevkivskyi ilevkivskyi added feature priority-1-normal topic-plugins The plugin API and ideas for new plugins labels Mar 1, 2019
@ilevkivskyi
Copy link
Member

Yes, this looks like a reasonable feature. The main problem with implementing will be likely avoiding import cycles.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature priority-1-normal topic-plugins The plugin API and ideas for new plugins
Projects
None yet
Development

No branches or pull requests

2 participants