tsh
tsh

Reputation: 4738

How to write Python type hint when a function change its paramter's type

Let's say I have a Python function which expect input a List[str], and change it into List[int]

def data_cleaning(data):
    for i in range(len(data)):
        data[i] = int(data[i])

How should I add type hint to this function? Should I write...

Any of these?

Upvotes: 1

Views: 1310

Answers (1)

user2357112
user2357112

Reputation: 280335

You've got a bigger problem. As far as static typing goes, changing a List[str] into a List[int] is a type error. Imagine what it would look like at the call site:

x: List[str] = ['1', '2', '3']
data_cleaning(x)

Now the x variable holds a List[int] when it was supposed to only hold values of type List[str].

There is no correct annotation for "changes List[str] to List[int]". At best, you can annotate data as List[Any], and call the function with an argument annotated as List[Any].

Upvotes: 2

Related Questions