[Python] How does one type hint a csv reader returned by csv.reader()?

Discussão em 'Python' iniciado por Stack, Maio 20, 2025.

  1. Stack

    Stack Membro Participativo

    How does one type hint a csv reader returned by csv.reader()? When I check the type of the result in python I see:

    >>> import csv
    >>> with open('upt.csv', newline='') as csvfile:
    ... reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    ...
    >>> reader
    <_csv.reader object at 0x10c5292e0>
    >>> type(reader)
    <class '_csv.reader'>
    >>> reader.__class__
    <class '_csv.reader'>
    >>> import _csv
    >>> _csv.reader
    <built-in function reader>
    >>> _csv.reader.__class__
    <class 'builtin_function_or_method'>


    So it describes the class type of reader as _csv.reader but when I import _csv.reader that is not a class it is a function. How do I make a type hint for the csv.reader class instance?

    The docs: https://docs.python.org/3/library/csv.html?highlight=csv#csv.reader do not describe the return type using a class.

    Oddly enough I do see class methods like __init__ and __new__ on the _csv.reader so maybe this is a c/c-binding issue? >>> dir(_csv.reader) ['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']

    Note: DictReader does not have this problem:

    >>> with open('upt.csv', newline='') as csvfile:
    ... dreader = csv.DictReader(csvfile)
    ...
    >>> dreader
    <csv.DictReader object at 0x10c410a30>
    >>> csv.DictReader
    <class 'csv.DictReader'>

    Continue reading...

Compartilhe esta Página