Types

Computers frequently handle different kinds of data.

similar to how there are different types of fruits, and different models of automobiles, there are different types of data that computers process.

Noteworthy types

typedescriptionexample
stra string of text. In modern Python all strings are unicode"I like pizza"
bytesrepresentation of an arbitrary stream of bytes. Frequently returned from low-level communication library calls.b'\xde\xad\xbe\xef'
intIntegers, may be positive or negative. In modern python, they may be of arbitrary size.42
floatDecimal numbers, represented as floating point values0.75
NoneThe lack of a value; roughly comparable to NULL in the C-like languages.None
boolBoolean values. Something that is either True or False.True, False
listOrdered collection of heterogeneous data. see lists[2,1,3,4]
dictKey-value pairs of heterogeneous. see dict{ 2: 'foo', 1: 'bar'}
setunordered collection of heterogeneous data. see sets{ 1, 2, 3}, {(1, 2), (1, 3), (4, 2)}

How do we use types?

  • Every expression in Python has a type
  • Types can typically be determined statically
  • Types allow your IDE/Editor to provide static-analysis features
# x is of type `int` because it is the result of adding two `int` literals together.
x = 4 + 3
# y is of type `float` because `/` between two ints produces a floating point result.
y = x / 4

# untrusted_input is of type `str` because that is what `input` returns.
untrusted_input = input("enter an option: ")

ide_types_tab_completion.png

Type annotation syntax for expressions

Modern python allows for variables to be annotated with types. These annotations serve as development documentation, and are utilized by static analysis tooling to help programmers write code.

The above code example can also, to be more verbose, written as:

x: int = 4 + 3
y: float = x / 4
untrusted_input: str = input("enter an option: ")
  • name: type denotes that name is an instance of type

Type annotations are intended for documentation and tooling; the Python interpreter does NOT enforce annotations at runtime.

# NOTE:   The following statement is erroneous, 
#         and is intentionally included for demonstrational purposes.
x: float = "I like pizza"

Further reading: