Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify the type of pandas series elements in type hints?

My function returns a pandas series, where all elements have a specific type (say str). The following MWE should give an impression:

import pandas as pd 
def f() -> pd.Series:
    return pd.Series(['a', 'b']) 

Within the type hints I want to make clear, that f()[0] will always be of type str (compared for example to a function that would returnpd.Series([0, 1])). I did this:

def f() -> pd.Series[str]:

But

TypeError: 'type' object is not subscriptable

So, how to specify the type of pandas series elements in type hints?. Any ideas?

like image 634
Qaswed Avatar asked Sep 09 '19 13:09

Qaswed


2 Answers

You can utilize typing.TypeVar to accomplish this:

from typing import (
    TypeVar
)

SeriesString = TypeVar('pandas.core.series.Series(str)')
def f() -> SeriesString:
like image 52
zfact0rial Avatar answered Oct 10 '22 10:10

zfact0rial


Unfortunately Python's type hinting does not support this out of the shelf. Nonetheless, you can always make use of dataenforce library (link) to add hints or even enforce validation.

like image 40
ibarrond Avatar answered Oct 10 '22 09:10

ibarrond