python / python/mypy

Plugin initialization hook

Open
#5,911 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature priority-2-low topic-plugins
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

I have already asked about augmenting AST with new nodes in the initialization hook for plugins in
https://github.com/python/mypy/issues/5910

I was able to figure it out with get_back_class_hook and dummy base class like here
https://github.com/mkurnikov/django-stubs/blob/master/django-stubs/conf/__init__.pyi#L7

There's another use case.
In Django there's an INSTALLED_APPS setting:

INSTALLED_APPS = ('app1', 'app2')

which specifies apps to use to retrieve model definitions for database schema (using models.py files).

Those could be used in the model definition code like this

from django.db import models

class User(models.Model):
    member = models.ForeignKey(to='app1.Model1')

In plugin, I can parse to= value, figure out the right type of a model, and set as return type of __get__ to have a proper value for member attribute.
For that I need to use lookup_fully_qualified
https://github.com/python/mypy/blob/master/mypy/semanal.py#L3453
and this requires module to be present in the self.modules list.

I need to create new MypyFile instances to populate that attr myself, but parse_file() method belongs to BuildManager class
https://github.com/python/mypy/blob/master/mypy/build.py#L648
and I wasn't able to find how to access it from the ClassDefContext.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with ClassDefContext and trace how it relates to BuildManager.parse_file() in mypy/build.py, then inspect lookup_fully_qualified() in mypy/semanal.py and the self.modules collection. The issue is complete when a plugin has a supported way to make configured Django app modules available for resolving model references.

Written by the indexing model from the issue text.

Assessment

Tech stack
django, python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.