Declaring Python variables with a specific type

Question:

Python allows me to make the following statement…

records = list()

ie declare a name/variable that is at present of type ‘List’

The following syntax does not throw a syntax error but I’m not sure what it actually does…

records: list()

Any ideas when you might use the colon version? Why is it syntactically correct if when I query its type I get an error?

records = list()
print(type(records)

>> <class 'list'>

records: list()
print(type(records)

>> NameError: name 'records' is not defined
Asked By: templegate

||

Answers:

In Python, the colon : is used to annotate the type of a variable. When you use the syntax records: [], you are declaring that the variable records is of type list, but you are not initializing it to any value.

However, if you try to print the type of records before initializing it, you will get a NameError because the variable is not defined yet. To avoid this error, you need to initialize the variable before trying to access its type.

Here’s an example of how to use the colon syntax to declare a variable with an initial value:

records: list = []
print(type(records))  # Output: <class 'list'>

This code declares the variable records with an initial value of an empty list, and the : list syntax annotates the type of the variable as list. When you print the type of records, you will get <class 'list'>.

While Python is a dynamically-typed language, type hints allow developers to add type information to their code that can be used to catch type errors and provide better tooling support.

When using type hints, you would typically annotate the type of a variable using the : syntax followed by the desired type. For example, you could annotate a variable records as a list of integers using the following syntax:

records: List[int] = []

This code declares the variable records as a list of integers, and initializes it to an empty list. The List[int] syntax specifies the type of the list, where int indicates the type of the elements in the list.

It’s worth noting that while type hints are primarily used for static type analysis, they can also be used at runtime using tools like typing. For example, you could use the typing module to check the type of a variable at runtime like this:

from typing import List

records: List[int] = [1, 2, 3]
assert isinstance(records, List)  # Returns True

This code imports the List type from the typing module, and uses it to annotate the records variable as a list of integers. The isinstance function is then used to check if the records variable is an instance of the List type at runtime, which returns True.

Answered By: angwrk
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.