Repository navigation
csv.DictReader and DictWriter not subscriptable at runtime #92391
Description
Activity
- addedtype-featureA feature request or enhancementA feature request or enhancement
on May 6, 2022 - addedstdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directory
on May 6, 2022 Why are they generic in typeshed?
Why are they generic in typeshed?
DictReaderhas been generic for a while.DictWriterwas made generic in python/typeshed#5366.The classes are slightly complicated to type, so I am not sure the stubs are 100% correct at the moment (I have a PR open at the moment to improve them). But I think it is correct that they are both generic. Copying what I wrote in python/typeshed#7787 (comment):
DictReaderseems pretty clearly like it should be generic -- the type that's returned fromDictReader.__next__depends very clearly on the type that you stick intoDictReader.__init__.In fact,
DictReaderseems like it could possibly be typed more correctly if it took another parameter: see python/typeshed#5994 (comment). (But that's irrelevant to the runtime; adding__class_getitem__will allow it to take any number of parameters at runtime.)I was confused about the implicit conversion to string in
DictWriter, which made me wonder ifDictWritershould be generic. ButDictWriterdoes some runtime typechecking in the_dict_to_listmethod before it does the implicit conversion to string. So I think it makes sense forDictWriterto be generic as well (as it is in the stub currently).I am not sure that they were designed this way. Why not return just
dict[Any, Any]inDictReader.__next__? The type of the result depends not only on the type of field names (which can have different types), but on types and values of other parameters and on the content of the file.The type of the result depends not only on the type of field names... but on types and values of other parameters and on the content of the file.
Can you give an example? If the stubs are incorrect, I would be interested in improving them.
The type of keys: the type of any item in
fieldnames(str | floatiffieldnamesis None), or the type ofrestkey.
The type of values:str | float,list[str|float], or the type ofrestval.
Feature or enhancement
Add PEP 585 style
__class_getitem__tocsv.DictReaderandcsv.DictWriter.Pitch
With PEP 585 most generic stdlib types are now subscriptable at runtime. Both DictReader and DictWriter are generic in typeshed but don't yet implement
__class_getitem__.Previous discussion