Python Function Definitions Don't Enforce Types

Day 5/30  This looked correct… until I actually ran it def add(a, b): return a + b Nothing looks wrong here. But then: add("10", 5) It fails Not when I wrote the function… not when Python read it… only when it ran. That’s how I learnt : ➡️ Function definitions don’t enforce types ➡️ The real check happens during execution So the code can look completely fine… and still break later. And that changes how you think about writing code #Python #LearningInPublic #Programming #Developers #30DaysofCode #CodingJourney

  • No alternative text description for this image

Python is an untyped language (shamelessly "dynamically" typed). What did you expect? Type is a set of values and operations defined on it. What are the types of a and b? What types + takes and returns? Furthermore Python's OO part is broken. Why it is "concatenate" and not "add" in the error message? Because it dispatches on the first argument and that happened to be string. If you called add(5,"10") the answer would be different. Isn't addition commutative? Oops, they used a wrong character for concatenation too! Use a carefully designed statically typed language like Ada and you will have no such problems anymore.

Yep, Python is dynamic. Type checking is done during execution. It has optional type checking if you want to employ that, but in turn, some dynamism is lost.

See more comments

To view or add a comment, sign in

Explore content categories