{"id":"3e10be3f07ab44f8","repo":"encode/httpx","slug":"invalid-type-for-name-expected-str-got-type-nam","errorCode":null,"errorMessage":"Invalid type for name. Expected str, got {type(name)}: {name!r}","messagePattern":"Invalid type for name\\. Expected str, got (.+?): (.+?)","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"httpx/_multipart.py","lineNumber":77,"sourceCode":"    if not content_type or not content_type.startswith(b\"multipart/form-data\"):\n        return None\n    # parse boundary according to\n    # https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1\n    if b\";\" in content_type:\n        for section in content_type.split(b\";\"):\n            if section.strip().lower().startswith(b\"boundary=\"):\n                return section.strip()[len(b\"boundary=\") :].strip(b'\"')\n    return None\n\n\nclass DataField:\n    \"\"\"\n    A single form field item, within a multipart form field.\n    \"\"\"\n\n    def __init__(self, name: str, value: str | bytes | int | float | None) -> None:\n        if not isinstance(name, str):\n            raise TypeError(\n                f\"Invalid type for name. Expected str, got {type(name)}: {name!r}\"\n            )\n        if value is not None and not isinstance(value, (str, bytes, int, float)):\n            raise TypeError(\n                \"Invalid type for value. Expected primitive type,\"\n                f\" got {type(value)}: {value!r}\"\n            )\n        self.name = name\n        self.value: str | bytes = (\n            value if isinstance(value, bytes) else primitive_value_to_str(value)\n        )\n\n    def render_headers(self) -> bytes:\n        if not hasattr(self, \"_headers\"):\n            name = _format_form_param(\"name\", self.name)\n            self._headers = b\"\".join(\n                [b\"Content-Disposition: form-data; \", name, b\"\\r\\n\\r\\n\"]\n            )","sourceCodeStart":59,"sourceCodeEnd":95,"githubUrl":"https://github.com/encode/httpx/blob/b5addb64f0161ff6bfe94c124ef76f6a1fba5254/httpx/_multipart.py#L59-L95","documentation":"Raised as `TypeError` by `DataField.__init__` when the multipart field `name` is not a `str`. Multipart form field names must be text (they become the `name=` parameter in the `Content-Disposition` header), so passing bytes, an int, or None for the field name is rejected up front.","triggerScenarios":"Building `data={123: 'value'}` (int key) or `data={b'key': 'value'}` (bytes key) and passing it to `client.post(url, data=..., files=...)`; or constructing `httpx._multipart.DataField(123, 'v')` directly.","commonSituations":"Keys coming from JSON/dict sources that use non-string keys; dataclasses/enums used as dict keys without conversion; porting code that accidentally iterates `items()` of a non-string-keyed mapping.","solutions":["Coerce keys to str before passing: `{str(k): v for k, v in data.items()}`.","Validate the data dict shape before the request: `assert all(isinstance(k, str) for k in data)`.","Convert enums: `data = {k.value: v for k, v in data.items()}` if keys are enums.","Avoid mixing the same dict for JSON (which may allow non-string keys after encoding) and multipart."],"exampleFix":"// before\nclient.post(url, data={user_id: 'on'})  # user_id is int -> TypeError\n\n// after\nclient.post(url, data={str(user_id): 'on'})","handlingStrategy":"validation","validationCode":"def normalize_form_keys(data: dict) -> dict:\n    bad = [k for k in data if not isinstance(k, str)]\n    if bad:\n        raise TypeError(f'non-str form field keys: {bad!r}')\n    return {str(k): v for k, v in data.items()}","typeGuard":"def form_keys_are_str(data: dict) -> bool:\n    return all(isinstance(k, str) for k in data)","tryCatchPattern":"try:\n    client.post(url, data=payload)\nexcept TypeError:\n    payload = {str(k): v for k, v in payload.items()}\n    client.post(url, data=payload)","preventionTips":["Coerce all form-data keys to str before the request.","Convert enum/non-str keys explicitly when building the payload.","Keep JSON-body dicts and form-data dicts separate to avoid key-type confusion."],"tags":["multipart","type-error","form-data","validation"],"analyzedSha":"b5addb64f0161ff6bfe94c124ef76f6a1fba5254","analyzedAt":"2026-08-04T19:32:56.768Z","schemaVersion":2}