SD 212 Spring 2023 / Notes


This is the archived website of SD 212 from the Spring 2023 semester. Feel free to browse around; you may also find more recent offerings at my teaching page.

Unit 12: Typing

1 Overview

This short unit will introduce the idea of type annotations in Python, where we can specify “hints” on what type a variable, function parameter, or return value should be.

As we will see, this functionality isn’t a “rule” that gets enforced by Python, but rather a tool that can help us write more clear and bug-free code.

It’s one of the newest features of Python, so there’s not too much about it in every book yet, but it is already well integrated into VS code.

2 Resources

3 Type checking your own code

  • In VS code: The pylance type checker comes installed alongside the standard Python tools, but you have to enable it!

    To enable “basic” checks, find the curly braces {} on the bottom status bar and turn type checking on:

    (If you want to enable “strict” type checking, you have to open your user settings, go to “extensions”, find “Pylance”, and scroll until you find the “type checking mode” and set it to “strict”.)

  • On the command line:

    First install mypy:

    mamba activate sd212
    mamba install mypy pandas-stubs

    Then you can type check any program like myprog.py by running:

    mypy --strict myprog.py

4 Examples

  • Function that takes a list of strings and a letter, and returns the number of strings in the list that start with that letter:

    def countstarts(words: list[str], letter: str) -> int:
        count: int = 0
        for word in words:
            if word.startswith(letter):
                count += 1
        return count
  • Function that takes any kind of number and prints a message indicating whether it’s at least 1 million:

    def saybig(x: int | float) -> None:
        if x >= 1000000:
            print(x, 'is big!')
        else:
            print(x, 'is not so big')
  • Midshipman class with a class variable to count the total size of the Brigade, two instance variables, and a function to return an email address string:

    class Mid:
        brigade_size: int = 0
    
        def __init__(self, name: str, alpha: int) -> None:
            Mid.brigade_size += 1
            self.name: str = name
            self.alpha: int = alpha
    
        def email(self) -> str:
            return f'MIDN {self.name} m{self.alpha}@usna.edu'