0

Recently I had a typehint problem for which the only solution I found is to make the typehint as a string:

import pandas as pd
def fun() -> pd.Series[str]: # returns an ERROR
    return pd.Series(['hola'])

def fun() -> "pd.Series[str]": # Does work and the IDE gets that whatever inside the series is a str
    return pd.Series(['hola'])

The solution was here: How to specify the type of pandas series elements in type hints?

However I didn't find any useful documentation not in pep nor in the python docs explaining this form of typehints as a string and why the first solution doesn't work but the second does.

In the docs they appear twice (typing.self, typing.TypeVarTuple chapters), but it is not explained how are they evaluated differently. Anyone knows why is like that? or where is this documented in the docs / pep? Or how is this feature called?

Ziur Olpa
  • 1,839
  • 1
  • 12
  • 27
  • What exactly is the error being returned…? – deceze Nov 25 '22 at 14:58
  • And, well, the difference is that the `[]` notation needs to actually be supported by the class when written as `pd.Series[str]`; if it doesn't explicitly support that, then that's an error, the same as any other invalid operation on an object. But when written as string, it's just a meaningless string, that your IDE and/or mypy impart some meaning on. – deceze Nov 25 '22 at 15:02
  • The question is not a duplicate, at least not with the ones suggested, I'm not asking how make typehints in python now in pandas. – Ziur Olpa Nov 25 '22 at 15:22
  • "TypeError: 'type' object is not subscriptable", is the error, which probably means your explanation @deceze is right but not very complete nor documented. I thought typehints were ignored at runtime, so it seems they aren't. – Ziur Olpa Nov 25 '22 at 15:24
  • The types are not *checked*, no. The type hints still need to be *valid expressions* though. If `pd.Series[str]` raises an error, then it'll do that, because it needs to be evaluated. – deceze Nov 25 '22 at 15:27
  • @deceze ok that makes sense, but that should be documented somewhere, at least in mypy, do you really think this question is duplicated? – Ziur Olpa Nov 25 '22 at 15:42
  • [*"Parameters may have an annotation of the form “: expression” following the parameter name. .. Functions may have “return” annotation of the form “-> expression” after the parameter list. __These annotations can be any valid Python expression.__"*](https://docs.python.org/3/reference/compound_stmts.html#function-definitions) – deceze Nov 25 '22 at 15:47
  • @deceze ok, that together with the second comment looks more like a proper answer, but do you really think this question is duplicated? – Ziur Olpa Nov 25 '22 at 16:22
  • If you maybe rephrased it to something like “why does this arbitrary type hint raise this error (error details here), I thought they aren’t being checked?”, it might be worth reopening. – deceze Nov 25 '22 at 16:35

0 Answers0