Blog

  • Reorder items in a list - Dec 13, 2024

    Lists in Python are ordered collections of items. You can reorder the items in a list using the sort method or by manually moving items around in the list. So let’s start with an example of how you can print an unsorted list as items at index 2 and 3 are not in order.

    Below is an example of how you can reorder items in a list with the sort method and is in this case sufficient as the items are sorted in ascending order. With the parameter reverse=True, you can sort the items in descending order. And with the parameter key, you can specify a custom sorting function.

  • Speeding up functions in Python - Jan 20, 2024

    Python’s versatility and ease of use make it a popular choice for a wide range of programming tasks. However, performance can sometimes be a concern, especially when working with large data sets or computationally intensive tasks. Repetitive calculations can be a particular problem, but Python provides a number of tools to help speed up these functions. One way is to use the functools.cache decorator to cache the results of a function which was introduced in Python 3.9. This can be used to avoid repeating calculations, and can significantly speed up the execution of a function.

    Lets take a look at a simple example. The following function calculates the factorial of a number and is a good candidate for caching. With the timeit module we can see how long it takes to run the function.

  • Using the itertools.batched function in Python 3.12 - Jan 15, 2024

    Python 3.12 introduced a new feature called itertools.batched() within the itertools module, which simplifies the process of creating iterators that return chunks (batches) of a given iterable. Before this function, developers typically had to write their own custom code to achieve the same result.

    Prior to Python 3.12, there were a few common ways to create batched iterators. One of the most popular and Pythonic methods involved a custom generator function. This approach was highly flexible and efficient, as it processed data lazily (on demand).

  • Format datetime easily - Dec 21, 2023

    Formatting datetime is a common task in Python and could be a daunting task for those new to Python. Especially when you need to format datetime in a specific way and looking at the documentation can be daunting for some. The example below shows how to format datetime in a specific way with the time.strftime() method, which can be complicated due to all the extra lines.

    Since the introduction of Python 3.6, there is a new way to format datetime with the f-string. This makes it easier to format datetime in a specific way. The example below shows how to format datetime in a specific way with the f-string.

  • Use dotenv to load environment variables - Nov 14, 2023

    Developing and deploying applications often requires the use of configuration variables such as passwords, API keys, and secret keys. These variables should not be hardcoded in the source code, as they can be accessed by unauthorized users. The dotenv library can be used to load environment variables from a file when it is started. This allows you to store sensitive information in a file that is not uploaded to a repository and to override the environment variables for development, testing, and debugging. This allows an application to be 12-factor compliant and to be deployed to different environments without changing the source code.

    As mentioned variables that contain sensitive information, such as passwords, API keys, and secret keys, should not be hardcoded in the source code. The example code below shows a hardcoded secret key and should not be uploaded to a repository.

  • How to use post-init with dataclasses - Oct 12, 2023

    By default a class in Python has an __init__ method that is called when the class is instantiated. This method is used to initialize the class attributes. The example below shows this in action and how a variable is set by combining two other variables.

    By upgrading a class to a dataclass, the __init__ method is automatically created and the class attributes are automatically initialized. This means that the full attribute is not set when the class is instantiated. The example below shows this in action and a common error that is raised when trying to setup the full attribute as self is not defined.

  • Using magic method __contains__ - Sep 07, 2023

    Python is a high level language and allows you to do a lot of things with ease. One of the things that Python allows you to do is to check if an item is present in a list or tuple for example. This is done using the in operator as shown below.

    This is a very simple and easy way to check if an item is present in a list or tuple. But what if you want to check if an item is present in a custom class? For this Python has a magic method called __contains__ which is used to check if an item is present in a container. This method is called when using the in operator.

  • The NAND, NOR, and XOR operators in Python - Apr 07, 2022

    The NAND, NOR, and XOR operators are logical operators that are not built into Python, but can be implemented using the built-in not, and, and or operators. The NAND operator returns True if and only if both of its operands are False, and the NOR operator returns True if and only if both of its operands are False. The XOR operator returns True if and only if exactly one of its operands is True.

    As can be seen in the truth table below, the NAND operator returns True if and only of its operands are False this is the opposite of the and operator. That is because the not operator is applied to the result of the and operator which inverts the result.

  • Convert numbers between numerical systems - Dec 11, 2021

    Learning to convert numbers between numerical systems is a fundamental skill in every programming language. Python provides built-in functions to convert numbers between binary, octal, decimal, and hexadecimal systems. While it seems like a simple task, it is essential to understand how to convert numbers between different numerical systems and how Python handles them.

    Python supports integer numbers, which are whole numbers without a fractional part. Integer numbers can be positive or negative. The integer type in Python is called int. The int type can represent numbers in different numerical systems, such as binary, octal, decimal, and hexadecimal.