7
Advanced, Overlooked Python Typing (martynassubonis.substack.com)
submitted 2 months ago by git@hexbear.net to c/programming@hexbear.net
top 1 comments
sorted by: hot top new old
[-] invalidusernamelol@hexbear.net 1 points 3 weeks ago* (last edited 3 weeks ago)

All my Python code is written this way and has been for about 3 years now. I do sometimes feel like I'm writing a different language than devs who just kinda use Python as a tool.

Having properly typed systems allows you to have surprisingly complex libraries of code that become zero headache to use since the linter immediately tells you what you need to give and what you get. If anything in that chain is broken, it tells you exactly where.

I see heavily typed and type reliant Python code as essentially instant unit testing. Especially if you just pepper in a bunch of assert statements (for simple checks it's faster and easier that getargs or reveal type).

If you type guard using asserts you also have runtime enforcement (that can be disabled with an interpreter flag).

There's also the benefit of being allowed to be a duck when you want. Your typing system shouldn't be thought of as part of your code, but as part of your test suite. If you have a situation that isn't reconcilable in it, you have a possible failure point and you'll be forced to add a #type: ignore tag hopefully with a description of why you're allowing a type inconsistency, but your code won't care that the defined types are wrong.

You can also use Protocol definitions to create duck type consistency that defines an interface kinda like C or Rust. A class/object will match the protocol as long as it has the methods and attributes required by the protocol.

You'll see a lot of that in the standard library type sheds and pyi files.

this post was submitted on 02 Dec 2025
7 points (100.0% liked)

programming

291 readers
12 users here now

  1. Post about programming, interesting repos, learning to program, etc. Let's try to keep free software posts in the c/libre comm unless the post is about the programming/is to the repo.

  2. Do not doxx yourself by posting a repo that is yours and in any way leads to your personally identifying information. Use reports if necessary to alert mods to a potential doxxing.

  3. Be kind, keep struggle sessions focused on the topic of programming.

founded 2 years ago
MODERATORS