django-stubs: Cannot mix URL patterns and included urlconfs
Bug report
What’s wrong
I cannot find a way to get the typing in urls.py right. It seems that a path that points to a view returns a URLPattern but a path that points to an included urlconf returns a URLResolver. So mixing both in a single list results in a List[object], for which mypy complains if you try to concatenate it with another list of url patterns.
For example the following:
urlpatterns = [
path("admin/", admin.site.urls),
]
if settings.DEBUG:
urlpatterns = (
[
path(
"media/<path:path>/",
django.views.static.serve,
{"document_root": settings.MEDIA_ROOT, "show_indexes": True},
),
path("__debug__/", include(debug_toolbar.urls)),
]
+ staticfiles_urlpatterns()
+ urlpatterns
)
Results in:
myproject/config/urls.py: error: Unsupported operand types for + ("List[object]" and "List[URLPattern]")
myproject/config/urls.py: error: Incompatible types in assignment (expression has type "List[object]", variable has type "List[URLResolver]")
myproject/config/urls.py: error: Unsupported operand types for + ("List[object]" and "List[URLResolver]")
How is that should be
The code above shouldn’t trigger any errors, or maybe a section could be added to the FAQ explaining how to get typing right in urlconfs.
System information
- OS: NixOS 20.09
pythonversion: 3.7.9djangoversion: 3.1mypyversion: 0.790django-stubsversion: 1.7.0
About this issue
- Original URL
- State: open
- Created 4 years ago
- Reactions: 8
- Comments: 15 (5 by maintainers)
I used this snippet, to bypass the problem:
I think you need to explicitly include the type for project_urls because of the way Variance and Union interact with inference in mypy:
project_urls: Sequence[Union[URLPattern, URLResolver]]] = [...I use * unpacking
Here you go:
Was it fixed though? I still experience the same error with
django-stubs1.9.0 installed. Also, I couldn’t find any related commit that would fix it.The workaround from micheller worked for me for
django-stubs1.8.0, but it appears that this is no longer necessary in the newly-releaseddjango-stubs1.9.0.