Skip to content

Literal of type string not accepted as keyword name #13674

Open
@twoertwein

Description

@twoertwein

To Reproduce

from typing import Literal

def fun(**kwargs) -> None:
    ...

class A:
    def __init__(self):
        self.a: Literal["a"] = "a"

    def test(self) -> None:
        return fun(**{self.a: "a"})  #  error: Keywords must be strings  [misc]

Your Environment

  • Mypy version used: 0.971

Activity

randolf-scholz

randolf-scholz commented on Jul 26, 2023

@randolf-scholz
Contributor

Also happens for dataclasses:

from dataclasses import dataclass
from typing import Literal, Mapping

@dataclass
class Foo:
    a: int
    b: int

x: Mapping[Literal["a", "b"], int] = {"a":1, "b": 2}
y: Foo = Foo(**x)  # error: Keywords must be strings  [misc]

https://mypy-play.net/?mypy=latest&python=3.11&gist=3450797f9c8ca85bb6b04240c8dadb88

randolf-scholz

randolf-scholz commented on Jul 26, 2023

@randolf-scholz
Contributor

This seems to be the relevant code:

mypy/mypyc/lib-rt/getargs.c

Lines 390 to 396 in b901d21

while (PyDict_Next(kwargs, &j, &key, &value)) {
int match = 0;
if (unlikely(!PyUnicode_Check(key))) {
PyErr_SetString(PyExc_TypeError,
"keywords must be strings");
goto latefail;
}

at other places _PyDict_GetItemStringWithError is used which wraps keyword argument in PyUnicode_FromString

static PyObject *
_PyDict_GetItemStringWithError(PyObject *v, const char *key)
{
PyObject *kv, *rv;
kv = PyUnicode_FromString(key);
if (kv == NULL) {
return NULL;
}
rv = PyDict_GetItemWithError(v, kv);
Py_DECREF(kv);
return rv;
}

JelleZijlstra

JelleZijlstra commented on Jul 26, 2023

@JelleZijlstra
Member

That is not the relevant code, as it is mypyc runtime code. This issue is about mypy, not mypyc. The error appears to be raised here:

mypy/messages.py:            self.fail("Keywords must be strings", context)

I haven't looked further.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @JelleZijlstra@twoertwein@randolf-scholz@AlexWaygood

        Issue actions

          Literal of type string not accepted as keyword name · Issue #13674 · python/mypy