You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hi, it seems that csv.DictWriter is assuming dictionary keys will always be strings
I've found it useful to use IntEnum keys with DictWriter to avoid having magic strings and write metadata rows positionally
I think it would make sense to change csv.pyi to change fieldnames and the key of _DictRow to be parameterize around a TypeVar('T')
I can add a pull request if you all think this is the right way to go
The dict keys can be any type compatible with _csv._writer.writerow, which is currently Any-typed in the stubs. But at runtime, it doesn't work with e.g. enum.Enum, even though it works with at least int, float and str (and also with IntEnum because it inherits from int). I guess you could use a typevar like this:
T = TypeVar("T", float, str)
This typevar can be for example str, float, int (because mypy thinks that int inherits from float even though it actually doesn't) and IntEnum (because it inherits from int). But it can't be enum.Enum.
I guess DictWriter should be made generic. Then your code would type-check as is because DictWriter(...) defaults to DictWriter[Any], and if you want better type checking, you could do DictWriter[MyEnum].
Activity
Akuli commentedon Jan 11, 2021
The dict keys can be any type compatible with
_csv._writer.writerow, which is currentlyAny-typed in the stubs. But at runtime, it doesn't work with e.g.enum.Enum, even though it works with at leastint,floatandstr(and also withIntEnumbecause it inherits fromint). I guess you could use a typevar like this:This typevar can be for example
str,float,int(because mypy thinks thatintinherits fromfloateven though it actually doesn't) andIntEnum(because it inherits fromint). But it can't beenum.Enum.I guess
DictWritershould be made generic. Then your code would type-check as is becauseDictWriter(...)defaults toDictWriter[Any], and if you want better type checking, you could doDictWriter[MyEnum].kanetkarster commentedon Jan 20, 2021
Awesome! I will take a stab at implementing this
Akuli commentedon May 7, 2021
Actually, it accepts any type, because the underlying
_csv.writer.writerowconverts everything to string:In your case, you needed
IntEnumto ensure thatMyEnum.foo == 0. It needs that for finding the key0from thefieldnameslist.