typestar

Dataclass with distance in Python

Dataclasses cut the boilerplate out of small value classes.

from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float

    def distance_to(self, other):
        return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5

How it works

  1. @dataclass writes __init__ and friends for free.
  2. Stores x and y coordinates.
  3. distance_to applies the Pythagorean theorem between two points.

Keywords and builtins used here

The run, in numbers

Lines
9
Characters to type
173
Tokens
53
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 32 seconds.

Type this snippet

Step 4 of 4 in Typing & dataclasses, step 23 of 53 in Pythonic Python.

← Previous Next →