Python Functions: 4 Tips For Writing Proper Functions That You Must Know
Introduction
Functions are an essential part of the Python programming language. A function is simply a block of code that performs a particular task. There are two types of functions in Python: built-in functions and user-defined functions. Built-in functions are part of the Python library. User-defined functions are functions that Python users can define using the keyword "def." In this article, we are going to talk about user-defined functions. We will look at four tips that can help you define functions that enhance the readability, maintainability, and testability of your code.
1. Make Your Functions Pure
User-defined functions can either be pure or impure. A pure function is a function that will return the same output given the same arguments. It has no side effects, such as printing to the console or modifying global variables. Here is a simple example of a pure function:
This function is pure because, for a given input x, it will consistently produce the same output.
On the other hand, impure functions can have different outputs for the same input, depending on the state of the program or the outside world. And they can have other side effects, such as printing on the console. Here is an example of an impure function:
This function is not pure because it has side effects. Besides returning the results, it is also printing x to the console. The printing is a side effect, making this function impure. It also relies on the external variable num (the global variable) when calculating the result. This means that given the same input (the value of x), the function can have different outputs if the external variable changes. In a pure function, the output is solely determined by the input parameters, and there are no dependencies on external states.
Why Should You Strive to Make Functions Pure?
Even though impure functions can be useful and necessary in some situations, they can be notorious for making code more difficult to understand, maintain, and test. As we have seen above, the behavior of an impure function can depend on factors that are outside of the function's control (e.g., global variables). Pure functions, on the other hand, are more predictable because their output is solely determined by their input parameters. Given the same inputs, a pure function will always produce the same result. This predictability makes it easy to understand the behavior of the code. Pure functions are also easy to debug because if a pure function is not producing the expected result, you can focus on the function itself and its inputs without worrying about external influences.
50 Days of Data Analysis with Python: The Ultimate Challenges Book for Beginners
The only way to master data analysis with Python is by doing challenges. This book is ideal for anyone who is serious about becoming proficient in data analysis, a sought-after skill in today's data-driven world. Take advantage of the December 50% discount.
2. Break Long Functions into Smaller Chunks
Sometimes you may be tempted to incorporate everything into one function. This can be particularly problematic when the function becomes too long. Longer functions offer several disadvantages for code readability, maintainability, and overall code quality. Let's say you want to define a to-do list function. This function will be able to display a menu of options, add tasks, remove tasks, mark tasks as complete, and so forth. Instead of putting everything in one function, you can break your code into smaller functions. Each small function will perform a specific task. Here is an example:
In this example, instead of piling everything into one function, we have created small functions, each dedicated to a specific task. This makes the code easier to understand. Debugging is also simpler with smaller functions. If an issue arises, you can narrow down the problematic area more quickly. This reduces the time and effort required to identify and fix bugs.
3. Use Docstrings
What is a docstring? Docstrings describe the purpose of the function, its parameters, return values, and any other relevant information. When defining functions, it is good practice to ensure that you add a docstring. Docstrings serve as documentation for your functions, making it easier for you or others to understand the purpose and functionality of a function, even after a long period of time. This can save time and effort when revisiting or modifying the function. Here is an example of a function with a docstring:
What we have inside the quotes is what is known as a docstring. This docstring not only explains what the function does but also documents the expected inputs and outputs of the function.
4. Use Type Hints
To improve documentation, you can add type hints to the function. Type hints are a way of specifying the expected types of parameters and return values for functions in Python. Here is an example:
In this example, the function has both a docstring and type hints. The str type next to the name parameter hints that the function expects a string argument. The str type (- > str) at the end hints that the function expects to return a string. Even though type hints are not enforced by the Python interpreter, they can be checked by static type checkers such as mypy. When you add type hints to your functions, other users of your code can quickly understand the intended data types, enhancing the clarity of your code.
Conclusion
These are some of the tips that you can incorporate into your functions to improve the readability, maintainability, and testability of your code. Thank you for reading. If there is any topic that you want to see in future articles, please comment below. Please like, share, and subscribe to this newsletter if you are not yet a subscriber.
Do you want to learn more Python tips that will improve your Python knowledge? Python Tips and Tricks: A Collection of 100 Basic & Intermediate Tips & Tricks is the resource that you need.
Here are some of the things you will like about the book:
The tips are easy to understand and follow.
The book is well-organized and easy to navigate.
The tips are practical and can be used in everyday programming.