Python Safety Net: How to Prevent Sneaky Errors

𝐃𝐚𝐲 𝟔/𝟑𝟎: 𝐇𝐨𝐰 𝐝𝐨 𝐏𝐲𝐭𝐡𝐨𝐧 𝐝𝐞𝐯𝐬 𝐡𝐚𝐧𝐝𝐥𝐞 𝐭𝐡𝐢𝐬? 🐍 Coming from C++, I’m used to the compiler being my safety net. If I try to add a string to an int there, the code won’t even run. ➡️ But yesterday I realized Python is... a different world! def add(a, b): return a + b add(10, "5")💣 Boom! Runtime Error In a tiny script, this is a 2-second fix.. But in a massive codebase with thousands of functions? This feels like a 𝐡𝐢𝐝𝐝𝐞𝐧 𝐫𝐢𝐬𝐤 𝐰𝐚𝐢𝐭𝐢𝐧𝐠 𝐭𝐨 𝐡𝐚𝐩𝐩𝐞𝐧. So, the real question for the experts here: How do you guys stop these "sneaky" errors before they hit production? Is it: A) Just remember everything B) Test everything thoroughly (Unit tests for every single edge case) C) Use Python type hints (a: int, b: int) (👀but do they actually stop the crash?) D) Something else(MyPy? Pylint?) I’ve been digging into this 𝐜𝐥𝐚𝐬𝐡 𝐛𝐞𝐭𝐰𝐞𝐞𝐧 𝐟𝐥𝐞𝐱𝐢𝐛𝐢𝐥𝐢𝐭𝐲 𝐚𝐧𝐝 𝐬𝐚𝐟𝐞𝐭𝐲 𝐭𝐨𝐝𝐚𝐲. I’m hunting for a way to make Python feel just as safe as C++. I'll share what I find tomorrow! Drop your choice below 👇 What’s the standard industry workflow for catching these? #Python #Cpp #LearningInPublic #30DaysOfCode #SoftwareEngineering #Programming

  • No alternative text description for this image

Learn to be Pythonic. Write fewer lines. Use the interpreter. Partially run to a breakpoint, develop from the breakpoint state, ... When approaching from another language Python is multi- paradigm, dynamic, and still strongly typed. There's a temptation to just stick with the subset of Python that is most like your other language, you need to go beyond that to get comfortable with Python. I would suggest you try Python from the Jupyter environment to immerse you in it's dynamic goodliness to break you from your static language compiler flow that you know.

Like
Reply

Mypy and hints are the go-to for modules and larger code bases. You can get away with just remembering everything for short scripts with very specific use cases though.

B - Test everything thoroughly

See more comments

To view or add a comment, sign in

Explore content categories