02 Python Typing
02 Python Typing
Annex
• Additional techniques
Section 1: Getting Started with Python
Click to edit Master title style
Typing
• Python is dynamically typed
• Providing type hints
• How to verify Python type usage
• Python types available
Python is Dynamically Typed
Click to edit Master title style
• Python is a dynamically-typed language
• A variable can change its type mid-flight
x = 42
print(x, type(x))
x = "Hello world"
print(x, type(x))
Ex01_PythonIsDynamicallyTyped.py
y = 43 # OK
y = "Hello" # Not OK
Ex02_ProvidingTypeHints.py
pyright <filename.py>
• For example:
Python Types Available
Click to edit Master title style
• You can define type hints for all the simple Python types:
a: int = 42
b: float = 3.14
c: bool = True
f: dict[str, str] = {"UK": "+44", "DK": "+45", "SE": "+46", "NO": "+47"}
print(a, b, c, d, e, f, g)
Ex03_PythonTypesAvailable.py
Section 2: Python Typing Techniques
Click to edit Master title style
• Defining type hints for functions
• Type techniques
• Defining type hints for methods
Defining Type Hints for Functions
Click to edit Master title style
• You can define types for function arguments/returns…
• Note:
• Optional and Any are located in the typing module
Type Techniques (2 of 2)
Click to edit Master title style
• You can define the signature of lambdas
• Via Callable in the typing module
from typing import Callable
class Person:
• An abstract class…
• Is a class you can't instantiate
• Instead, you instantiate concrete subclasses
• An abstract method…
• Is a method specified (but not implemented) in an abstract
class
• All concrete subclasses must override/implement the method
Defining an Abstract Class
Click to edit Master title style
• Python has a handy module named abc
• Helps you define abstract classes and abstract methods
class shape(abc.ABC):
@abc.abstractmethod
def area(self: Self) -> float: ...
@abc.abstractmethod
def perimeter(self: Self) -> float: ...
Ex07_AbstractClass.py
Defining Concrete Classes
Click to edit Master title style
• To define a concrete subclass:
• Inherit from a superclass
• Provide an implementation for all abstract methods
👍
class quadrilateral(shape):
class circle(shape):
Ex08_ConcreteSubclasses.py
Click to edit Master title style
Summary
def __init__(self: Self, name: str, id: int, salary: int) -> None:
self.name = name
self.id = id
self.salary = salary
class Employee:
def __init__(self: Self, name: str, id: PK, salary: Money) -> None:
self.name = name
self.id = id
self.salary = salary
@overload
def seconds_to_midnight(p1: int) -> int: ...
@overload
def seconds_to_midnight(p1: int, p2: int, p3: int) -> int: ...
NUM_SECS_IN_DAY = 60*60*24