Is there a way to show the IDE which Type of Objects are in a List, so it colors / autocompletes properly?

Question:

I recognize from c# that you could do

(int)(randomVariable + 1 + anythingElse)

and the IDE would understand that the named variable/result is an integer.

Now in Python I want to let my IDE know, that in the list ceDocs which I am sending as a parameter will be objects of the class Doc so I can use autocomplete and proper coloring instead of "any" everywhere.


def createDocuments(ceDocs):
    for doc in ceDocs:
        doc.name = doc.path # example action

createDocuments(getFromPath(path))

Is there a way to do this in python?

Please correct me if this makes no sense… 🙂

Asked By: Tell is happy.

||

Answers:

Use type hints with the typing module.

from typing import List

class Doc:
   # ...

def createDocuments(ceDocs: List[Doc]):
    for doc in ceDocs:
        doc.name = doc.path # example action
Answered By: puncher

For python 3.10:

def createDocuments(ceDocs: list[Doc]):
    for doc in ceDocs:
        doc.name = doc.path # example action

For earlier versions:

from typing import List

def createDocuments(ceDocs: List[Doc]):
    for doc in ceDocs:
        doc.name = doc.path # example action
Answered By: Ofer Sadan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.