Home > OS >  How to specify type/className when using for to iterate a python list
How to specify type/className when using for to iterate a python list

Time:03-20

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 ? - 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

  • Related