Comment

Comment by jon-wood

You can use types for this in Python:

  def do_something(position: ValidatedPosition):
    ...

  position = Position(x, y)
  if abs(position.x) > 1 or abs(position.y) > 1:
    raise ValueError("out of bounds")

  position = ValidatedPosition(position.x, position.y)
  
  do_something(position)
In practice I'd probably have ValidatedPosition encapsulate that validation in it's constructor, but you get the idea. If you attempt to pass a Position to do_something then mypy is going to shout at you for passing an object of the wrong type to it.

Python's type checking definitely isn't as comprehensive as something like Rust, but I have found it increasingly useful for situations like this where you want to ensure the data being passed in has been appropriately handled.

parent jon-wood 3 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton