pie, tart, apple, flat lay, food, bake, pastry, blue food, blue apple, pie, pie, pie, pie, pie, tart, flat lay

Type Like a Pro: Validations That Save Your (Pie)thon Code

Oh, I love my pie. What- wait, my pie?

No, Mypy!

Mypy is a Python module that allows you to add type validations to your Python code using annotations.

But a waah Type Validation? / What is Type Validation?

Programming languages represent different types of data within programs by using datatypes. Datatype constrains pieces of data to be a specific type of data, such as a number, a character, or a string. This restriction helps to ensure the proper execution of computer codes. Furthermore, datatypes determine different operations that may be performed on program data, such as finding the length of a string.

Let’s say you wanted to add two numbers; the addition operation is done on the two pieces of data of a numeric datatype. Using the incorrect datatypes would result in unexpected results or errors.

Check dis out / Look at this

PYTHON VS C# VARIABLE DECLARATION

Notice the difference in the declaration for the sum variable?

Python doesn’t specify a datatype for the sum variable, whereas C# specifies the int datatype. This is because C# is a strict-typed language, while Python is a dynamically typed language. The Python interpreter automatically assigns the correct int datatype to the sum variable at runtime.

However, if one of the operands is changed to a string, the code gives an error. This is because the addition operator (+) doesn’t work on mixed data types.

Luk Yah / Look Here

int 8 is now changed to string “8”
PYTHON EDITOR
C# EDITOR

In the C# code editor, there is a red underline indicating that there is an error even before running the code. Python, however, will only realize this error at runtime. Thus, if not managed properly, a dynamic typed language such as Python can be used to write programs that are more prone to errors or unexpected behaviors. This is where Type Validations come in.

Type validation is the process whereby coders can annotate program data such as variables, function parameters and return types, by specifying required datatypes.

Type validations are used solely to give type semantics to program data using annotations to help coders write more robust error-free programs.

Benefits of Type Validations

Improved Readability

Type annotations specify the expected types for variables or function inputs and outputs. This allows for the code to be more easily read and understood, especially by future coders. Type annotations also provide an in-built documentation for the code base reducing the need to source external documentation.

Better Code Quality

Bugs can be caught early during development when using type checking, rather than at runtime. Enforcing types ensures that inputs and outputs are consistent, leading to fewer runtime errors.

Enhanced Developer Productivity

IDEs (Integrated Development Environments) and code editors can provide better autocompletion, tooltips, and refactoring capabilities, when type annotations are used, making development faster and more efficient.

Type-checking tools (like Mypy or Pyright) can automatically verify your code for type errors without having to run the program, reducing the time spent debugging.

Easier Refactoring

Specifying clear type definitions helps to ensure that refactoring code changes are consistent across the codebase. It’s easier to update a function signature when you know the exact types it deals with.

Better Maintenance

Type validations help maintain large codebases. As your project grows, having types enforced throughout your system helps new developers or teams quickly understand how the system is expected to behave, minimizing the learning curve.

Consistent type-checking leads to fewer unexpected behaviors when the code is modified or extended.

Documentation

Type annotations essentially act as in-code documentation for function signatures. This provides clarity on what types are expected without requiring a developer to look up additional documentation. This can be particularly useful in larger teams, where developers may need to understand the behavior of a function or method quickly.

Python’s Type Validation Tools

Mypy: A static type checker for Python that checks your code for type errors based on type annotations.

Pyright: Another popular type checker that integrates well with Visual Studio Code.

Pylint: While primarily a linter, Pylint also provides type checking if you’re using type annotations.

Mypy

To get started with Mypy, you have to first install it. Mypy requires Python 3.9 or later to run.

python3 -m pip install mypy

Afterward, you can run it by using the Mypy CLI tool.

mypy national_dish.py

Executing the above command allows Mypy to check the nationa_dish.py file and print out any errors it discovers.

Mypy however, is a static type checker, so Mypy checks Python code for errors without ever running the code. Mypy has little or no effect on plain dynamically typed Python code. This means to get a meaningful diagnosis from Mypy, type annotations must be added to Python code.

Seeit Yah / Here it is

DEFINING AND INVOKING prepare_national_dish FUNCTION WITH TWO DIFFERENT ARGUMENTS.

Both function calls will fail at runtime, but Mypy will not report an error since “prepare_national_dish” function does not have type annotations. When this script is executed, we get the following TypeError:

TYPE ERROR THROWN ONLY AT RUNTIME IN PYTHON

The TypeError is thrown because the integer value 123, passed into the prepare_national_dish function, is being added to the string value “Ackee”. Python assumes you are trying to concatenate the two values, treating them as strings.

Thus, add type annotations (type hints) to allow Mypy to detect these bugs before running the script.

TYPE ANNOTATIONS ADDED

Now prepare_national_dish function indicates that it accepts a string and returns a string value. Mypy will now detect the incorrect use of the prepare_national_dish function and the misuse of the variables used inside the function. So let’s run the Mypy CLI on the annotated prepare_national_dish function.

mypy national_dish.py

MYPY OUTPUT

The Mypy CLI outputs detected errors before executing the Python script, helping to find bugs at development time instead of at runtime.

The Mypy type checking process can be improved further by installing and enabling the Mypy vscode extension. This extension will highlight potential bugs as you type your Python code, thus aiding in writing faster, robust code.

MYPY VSCODE EXTENSION ENABLED

With the Mypy vscode extension enabled, the invalid inputs to the prepare_national_dish function call are quickly underlined in red, alerting the coder that errors exist. This will help coders to fix all errors before executing the code.

All in all, using type validation in Python helps create more reliable, maintainable, and efficient code, especially as projects scale. It doesn’t make Python a statically typed language, but it brings many benefits that improve the development experience and the quality of the final product.

jacoder
jacoder
Articles: 4

2 Comments

  1. I appreciate how you break down complex topics! It’s similar to how Helmet Royale makes challenging gameplay accessible. Thank you for sharing your expertise!

Leave a Reply to ScarlettCancel Reply

Your email address will not be published. Required fields are marked *