baxx
baxx

Reputation: 4745

Typehint list with strings and lists of strings in mypy

How would one type hint the following:

def f(x : <type>) -> None: print(x)

Where x is a list containing strings, and lists of strings.

Eg:

# example 1
['a', 'sdf', ['sd', 'sdg'], 'oidsf d', 'as', ['asf','asr']]
# example 2
[['as', 'asfd'], ['oei', 'afgdf'], 'egt', 'aergaer']

Upvotes: 1

Views: 922

Answers (1)

Samwise
Samwise

Reputation: 71542

The type you want is Union:

from typing import List, Union


def f(x: List[Union[str, List[str]]]) -> None:
    print(x)


f(['a', 'sdf', ['sd', 'sdg'], 'oidsf d', 'as', ['asf', 'asr']])
f([['as', 'asfd'], ['oei', 'afgdf'], 'egt', 'aergaer'])

A List[Union[str, List[str]]] is "a list of items that can be either strings or lists of strings".

Upvotes: 2

Related Questions