DEV Community

loading...

Problem with unknown import symbols in PyLance and Django

Pavel Morava
・1 min read

Problem

I happened to have an issue with PyLance in VS Code. See the line below.

from django.shortcuts import reverse
Enter fullscreen mode Exit fullscreen mode

Even though you can import reverse function like this, PyLance starts complaining

"reverse" is unknown import symbol
Enter fullscreen mode Exit fullscreen mode

It kept bugging me, so I have decided to open an issue on Github.

The solution

Since I was importing reverse from django.shortcuts instead of django.urls, the type stubs did not work correctly.

To correct the unpleasant situation, I was only required to change the import statement like this:

from django.urls import reverse
Enter fullscreen mode Exit fullscreen mode

Discussion

Thanks to Eric Traut I learned what the problem was.

It looks like you have type checking enabled and the django-stubs type stubs installed.

These stubs indicate that ObjectDoesNotExist is exported from django.core.exceptions, not from django.db.models. And reverse is exported from djago.urls, not from django.shortcuts.

If you import these symbols from the modules where they are exported, these errors will go away.

It is likely that these other modules happen to also import (and implicitly re-export) these symbols at runtime, but you shouldn't rely on this behavior because it could change as the library evolves. The type stubs should indicate the proper (intended) import locations for these symbols as intended by the library authors.

Discussion (2)

Collapse
aheisleycook profile image
privatecloudev

i tried django for awhile in my python days its great framework for many thing but i takes alot time to build things but it has alot of good features bulin. nice sol

Collapse
aheisleycook profile image
privatecloudev

I like PHP or flask,