[Python] Can a Python value be annotated with its type without assigning it to a variable?...

Discussão em 'Python' iniciado por Stack, Março 14, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working with a Pandas DataFrame where the index is guaranteed to be the first day of a year. I want to change the index to be the year itself. The code is straightforward enough, and runs fine:

    import pandas as pd

    df = pd.DataFrame(data={
    'col1': [1, 2, 3],
    'col2': ['a', 'b', 'c'],
    }, index=pd.date_range(start='2023-01-01', periods=3, freq='YS'))

    df.index = df.index.year.set_names('Year')


    However, my code editor cannot infer the type of the .year property or the .set_names() method, because it can only infer df.index as an Index, and .year is only a property of its subtype DatetimeIndex. This irks me.

    A type hint can clarify things for the editor, or anyone reading:

    idx: pd.DatetimeIndex = df.index
    df.index = idx.year.set_names('Year')


    But it seems poor form to include an extra variable as an intermediate step solely for the type hint, when the original line is already quite short.

    In TypeScript, this could be done inline with a type assertion, like so:

    df.index = (df.index as pd.DatetimeIndex).year.set_names('Year')


    Does Python have any similar way of supplementing automatic type inference?

    Continue reading...

Compartilhe esta Página