Skip to content
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

Unable to use inlineformset_factory's returned class as baseclass for another class #1009

Open
maziar-dandc opened this issue Jun 21, 2022 · 3 comments
Labels
bug Something isn't working

Comments

@maziar-dandc
Copy link

Bug report

What's wrong

Cannot use the class returned from inlineformset_factory as a baseclase for creating another class, failing test:

- case: inlineformset_factory_extended
  main: |
    from typing import Any, Type
    from django import forms
    from myapp.models import Article, Category
    ArticleFS: Type[forms.BaseInlineFormSet[Article, Category, Any]] = forms.inlineformset_factory(Category, Article)
    ArticleFS(instance=Article())  # E: Argument "instance" to "BaseInlineFormSet" has incompatible type "Article"; expected "Optional[Category]"
    class CustomArticleFS(ArticleFS): # It will throw a "ArticleFS" is not a valid type error here.
      def __init__(self, *args, **kwargs):
        print('hi')
        super().__init__(*args, **kwargs)
    fs = CustomArticleFS(instance=Category())
    reveal_type(fs.instance)  # N: Revealed type is "myapp.models.Category"
  installed_apps:
    - myapp
  files:
    - path: myapp/__init__.py
    - path: myapp/models.py
      content: |
        from django.db import models

        class Article(models.Model):
            pass
        class Category(models.Model):
            pass

@sterliakov has provided some very helpful context here in this comment
#976 (comment)
related issue on mypy linked y @sterliakov: python/mypy#2813
related question on stackoverflow: https://stackoverflow.com/questions/59634937/variable-foo-class-is-not-valid-as-type-but-why

How is that should be

Should be able to use a dynamic class as baseclass for creating new classes, I guess as long as that baseclass's type is known.

System information

  • OS:
  • python version: 3.8
  • django version: used django-stubs environment at this commit hash
  • mypy version: 0.961
  • django-stubs version: 1.12.0
  • django-stubs-ext version: 0.4.3
@maziar-dandc maziar-dandc added the bug Something isn't working label Jun 21, 2022
@MaziyarMK
Copy link

python/mypy#2477

@sobolevn
Copy link
Member

If anyone wants to write a custom get_dynamic_class_hook() plugin hook for this, I am open to accept a PR :)

@maziar-dandc
Copy link
Author

that's my personal account, found a link and thought I'd add it here for reference.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Development

No branches or pull requests

3 participants