4

I don't know annotation of the empty array by typing module.

Sometimes, I'm using the list as a container of data.

it's like

box = []

def fuga(box):
    """box is container of processed data in this function"""
    for _ in range(10):
        res = hoge(_) # API response 
        box.append(res) 
    return box

So far I wrote this code as following,

from typing import List

box = []

def fuga(box: list) -> List[str]: 
    for _ in range(10):
        res: str = hoge(_)
        box.append(res)
    return box

It works well, but it's not appropriate python coding by typing module, I guess. This is because it's difficult for developer to understand what objects the variable "box" has. So, I think the appropriate annotation is

from typing import List 

box = []

def fuga(box: List[None]) -> List[str]: 
    for _ in range(10):
        res: str = hoge(_)
        box.append(res)
    return box

Is it collect or not? And if it's wrong, I want to know how to annotate empty array object as an argument.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

1 Answers1

2

First off don't define the list outside the method.. otherwise your method will have side effects on multiple calls.

Secondly, if you're going to use the variable, don't call it _. That name is by convention used for types that you will never use.

On to the actual type hinting! If you create an empty list, then the type inference isn't smart enough to guess what it will be eventually used for. That means it defaults to List[Any]. Instead declare it explicitly:

def fuga() -> List[str]: 
    box: List[str] = []
    for i in range(10):
        res: str = hoge(i)
        box.append(res)
    return box

In the example above I removed box from the parameters. If you did want it to be passed in then you should rename it. As it stands it will shadow the global variable which is bad practice. Try something like this instead:

box: List[str] = []

def fuga(input_box: List[str]) -> List[str]: 
    for i in range(10):
        res: str = hoge(i)
        input_box.append(res)
    return input_box
flakes
  • 21,558
  • 8
  • 41
  • 88