Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good idea to use a type alias name in python and then declare that as a variable?

I am looking at code like this:

class DeckManager:

   decks: Dict[str, Any]

   def __init__(self, col: a) -> None:

        self.decks = {}

Is it correct that decks: Dict[str, Any] is specifying a Type Alias? If so then does it make sense to use: self.decks later in the code. Is that not confusing?

like image 787
Alan2 Avatar asked Nov 30 '25 02:11

Alan2


1 Answers

No, decks is not a type alias. It is a type-annotation. According to PEP-484:

Type aliases are defined by simple variable assignments.

Or according to the typing documentation:

A type alias is defined by assigning the type to the alias.

So assigning to a variable anything that would be a valid type annotation is a type alias:

decks = Dict[str, Any]

This way decks would be a type alias.

But when you use the colon, you are annotating that variable, not creating a type alias:

decks: Dict[str, Any]

According to Python's type annotation conventions, you've simply annotated the decks attribute for DeckManager instances to have type Dict[str, Any].

like image 192
juanpa.arrivillaga Avatar answered Dec 02 '25 17:12

juanpa.arrivillaga