'Problem while using mypy with my django project

I have implemented mypy in my django rest framework but I am getting errors ModuleNotFoundError: No module named 'config' while running mypy.Is there any wrong with my django_settings_module in my mypy.ini file ?

I used to run my project with the command python manage.py runserver --settings=config.settings.development which was working fine but while configuring this setting in the mypy it is giving me error. What I might be doing wrong ?

Any help would be appreciated.

mypy.ini

[mypy]

plugins =
    mypy_django_plugin.main,
    mypy_drf_plugin.main

ignore_missing_imports = True
warn_unused_ignores = True
strict_optional = True
check_untyped_defs = True
follow_imports = silent
show_column_numbers = True

[mypy.plugins.django-stubs]

export PYTHONPATH=$PYTHONPATH:D:\DjangoProjects\project\config

django_settings_module = config.settings.development

settings directory

/project
 /config
  __init__.py
  urls.py
  wsgi.py
  /settings
    __init__.py
    base.py
    development.py

wsgi.py

app_path = os.path.abspath(
        os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir)
        )
sys.path.append(os.path.join(app_path, "project"))

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')

application = get_wsgi_application()


Solution 1:[1]

If anybody happens to run into this and was as confused as I am, here is what I did to make sure the mypy django plugin works.

I indeed had to add my project root to PYTHONPATYH, such that the plugin will be able to find your project. But let me clarify. In windows, you can search for 'environment variables' and create an environment variable named PYTHONPATH there, or edit the one that is already there with an added path.

I had been banging my head against the walls for a couple hours, because I didn't know how to properly set the PYTHONPATH. When you add this variable, make sure it is the full path, and that the folder you're specifying is the folder that includes manage.py For me, that was C:\Users\...\myproject (without the trailing slash).

I hope that works and that I can save someone from wasting hours of their life like I did.

Solution 2:[2]

Adding my two cents here - in my case I was running a system-wide mypy instead of the one from virtualenv:

Even though I was in the virtualenv

(env) ?  project git:(develop) ?  which python
/Users/Kramer/Documents/projects/example/env/bin/python

Mypy was not aliased:

(env) ?  project git:(develop) ?  which mypy
/usr/local/bin/mypy

The solution was to either:

  1. run mypy directly
(env) ?  project git:(develop) ? ../env/bin/mypy .
  1. ensure that you have all the dependencies installed in the system-wide python installation

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hendrik
Solution 2 Jack L.