Search code examples
pythontype-hinting

How to specify several string options for an argument in Python Type Hinting


I want to set up only a limited range of options for an argument in a method of Python. For example, how can I write it so the kind argument can only set to 'image' and 'video'

def get_all_creatives_from_accounts(self, 
                                    accounts = None,
                                    kind: Union['image', 'video'] = "video",
                                    limit_per_page=100) -> pd.DataFrame)

Solution

  • Use typing.Literal:

    from typing import Union, Literal
    
    def get_all_creatives_from_accounts(self, accounts=None,
        kind: Literal["image", "video"] = "video",
        limit_per_page=100) -> pd.DataFrame):