'How to specify type/className when using for to iterate a python list

I know python is dynamically typed language but want to know if this is possible, lets say I have a list of class Person called people

people = []

people.append(Person('james'))

for p in people :
    p.name = p.name + '_'

Is there a way to specify the type of p, something like this:

for p:Person in people :
    p.name = p.name + '_'

The reason I ask for this is because p seems to be treated as type any/object by the IDE, no property is being recognized by the intellisense when I type p. I'm using vsCode with the python plugin

Could a list comprehensions help me solve this or is this just a problem with the IDE not detecting the type ? - https://stackoverflow.com/a/30129220/17205969



Solution 1:[1]

You can accomplish this by adding a type annotation to the list when you declare it, like:

from typing import List


class Person:
    def __init__(self, name: str) -> None:
        self.name = name


people: List[Person] = []

people.append(Person("james"))

for p in people:
    p.name = p.name + "_"

In VS Code I can see the name property in the IntelliSense autocomplete: IntelliSense on name property

The loop variable, p, is also recognized as being of type Person: Loop variable p has type Person

If you inline the list declaration via a list comprehension the generic type of the list can be inferred and you can drop the type hint entirely:

people = [Person("james") for i in range(10)]

Generic type inferred

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1