The attrs.field converter parameter does not support higher-order functions.
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
mypy marks a field conversion higher-order function as unsupported when it is correctly written with the annotations.
the message is: Unsupported converter, only named functions, types and lambdas are currently supported
To Reproduce
from typing import Any, Callable, List, TypeAlias, TypeVar, cast
from attrs import define, field
T = TypeVar('T')
ItemConv: TypeAlias = Callable[[Any], T]
@define # positional only # class that resembles a mutable NamedTuple
class Media:
mediaType: int
name: str
... # more methods
def media_list_converter(raw: List[List[Any]]) -> List[Media]:
return [Media(*value) for value in raw]
def not_none(factory: Callable[[], Any], callback: ItemConv[T]) -> ItemConv[T]:
def converter(raw: Any) -> T:
if raw is None:
return cast(T, factory())
return callback(raw)
return converter
@define(kw_only=True)
class Foo:
mediaList: List[Media] = field(factory=list, converter=not_none(list, media_list_converter)) # error
obj = Foo(mediaList=[
[1, 'the filename'] # more values ...
])
print(obj) # output: Foo(mediaList=[Media(mediaType=1, name='the filename')])
Expected Behavior
I was hoping mypy would support the nested converter function that returns not_none.
Actual Behavior
>>> mypy media-test.py --strict
media-test.py:25: error: Unsupported converter, only named functions, types and lambdas are currently supported [misc]
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used: 1.8.0
- Mypy command-line flags: --strict
- Mypy configuration options from
mypy.ini(and other config files): not used - Python version used: 3.11.4
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the error from the provided media-test.py example with mypy --strict and Python 3.11.4. Trace how mypy validates the attrs.field converter expression, especially the nested function returned by not_none. Done means the example type-checks without the unsupported-converter error while preserving converter type checking.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 48/100