Home > OS >  The correct way to default None in Python 3.10 type hinting
The correct way to default None in Python 3.10 type hinting

Time:10-24

My understanding is that in Python >= 3.10, I can use | for default None (e.g., this question).

def abc(str | None) -> str:
    pass

I have the following example:

import pandas as pd
from typing import Iterable

def winsorise_df(df: pd.DataFrame, level: float = 0.01, exc: Iterable[str] | None) -> pd.DataFrame:
    pass

This returns error SyntaxError: non-default argument follows default argument. However, the following works:

def winsorise_df(df: pd.DataFrame, level: float = 0.01, exc: Iterable[str] | None = None) -> pd.DataFrame:
    pass

My interpretation is Iterable[str] | None tells Python that exc can be an iterable or None but I need to actually set the default value as None?? I would have thought because Iterable[str] | None is interpreted as Optional[Iterable[str]], it's implicit that default value is None. What is the correct way to set default value to None?

CodePudding user response:

I would have thought because Iterable[str] | None is interpreted as Optional[Iterable[str]], it's implicit that default value is None.

You think wrong. It's not. You need to specify the default value.

  • Related