Skip to content

Commit b4348cd

Browse files
try and use named arguments from caller for matching name (#24)
Co-authored-by: Anthony Sottile <[email protected]>
1 parent be47027 commit b4348cd

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

mypy_django_plugin/lib/helpers.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from mypy.nodes import (
1111
GDEF,
1212
MDEF,
13+
ArgKind,
1314
AssignmentStmt,
1415
Block,
1516
ClassDef,
@@ -175,6 +176,12 @@ def get_call_argument_by_name(ctx: Union[FunctionContext, MethodContext], name:
175176
Return the expression for the specific argument.
176177
This helper should only be used with non-star arguments.
177178
"""
179+
# try and pull the named argument from the caller first
180+
for kinds, argnames, args in zip(ctx.arg_kinds, ctx.arg_names, ctx.args):
181+
for kind, argname, arg in zip(kinds, argnames, args):
182+
if kind == ArgKind.ARG_NAMED and argname == name:
183+
return arg
184+
178185
if name not in ctx.callee_arg_names:
179186
return None
180187
idx = ctx.callee_arg_names.index(name)

tests/typecheck/fields/test_related.yml

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -800,6 +800,31 @@
800800
class User(AbstractUser):
801801
pass
802802
803+
- case: nullable_foreign_key_with_init_overridden
804+
main: |
805+
from myapp.models import A
806+
reveal_type(A.objects.get().b) # N: Revealed type is "Union[myapp.models.B, None]"
807+
installed_apps:
808+
- myapp
809+
files:
810+
- path: myapp/__init__.py
811+
- path: myapp/models.py
812+
content: |
813+
from typing import Any, TypeVar
814+
from django.db import models
815+
816+
_ST = TypeVar("_ST", contravariant=True)
817+
_GT = TypeVar("_GT", covariant=True)
818+
819+
class FK(models.ForeignKey[_ST, _GT]):
820+
def __init__(self, *args: Any, **kwargs: Any) -> None:
821+
kwargs.setdefault('on_delete', models.CASCADE)
822+
super().__init__(*args, **kwargs)
823+
824+
class B(models.Model): ...
825+
826+
class A(models.Model):
827+
b = FK(B, null=True, on_delete=models.CASCADE)
803828
804829
- case: related_manager_is_a_subclass_of_default_manager
805830
main: |

0 commit comments

Comments
 (0)