Using Exceptions instead of Dynamic Typing

Posted on Mon 17 May 2021 in Better Python

Photo

Python's dynamic typing is great, right? You can just do whatever you want with variables. FREEDOM! ;-) This comes at a price though, and sometimes one we're not always aware of.

Trying not to fail

For years I took advantage of Python's dynamic typing by having functions return an error state via a different data type. For example:

def double(int_input):
    if not isinstance(int_input, int):
        return "An integer must be provided"

    return int_input * 2

And consuming this function would have looked like this:

doubled_int = double(user_input)
if isinstance(doubled_int, str):
    print("You did not provide an integer")
    return

print(f …

Continue reading

Early Exit

Posted on Sun 12 July 2020 in Better Python

Photo

You will have definitely come across the following pattern often:

if post_data:
    thing = post_data.get("thing")
    if thing is not None:
        setting = get_user_setting(user, thing)
        if setting is not None:
            permission = get_user_permission(user)
            if permission is True:
                if user.is_superuser:
                    return DataPoint.objects.all()
                elif user.is_staff:
                    return DataPoint.objects.filter(user=user)
                else:
                    return DataPoint.objects.filter(user=user, thing=thing)
            else:
                return "Permission denied"
        else:
            return "Setting not found"
    else:
        return "Thing not specified"
else:
    return "No data posted"

What is good about the code above? It follows the thought process that most developers would have: which conditions …


Continue reading

Faster updating of dictionaries

Posted on Thu 09 July 2020 in Better Python

Photo

When updating a dictionary, no one would object to this:

ages["Pete"] = 42

But what about this?

ages["Tom"] = 29
ages["Linda"] = 37
ages["Pam"] = 62
ages["Coraline"] = 21

Still fine, right? There is another way of writing this, using the .update() method.

ages.update(
    {
        "Tom": 29,
        "Linda": 37,
        "Pam": 62,
        "Coraline": 21,
    }
)

Which one do you prefer? Would you say it's a matter of preference? I always preferred using the .update() method when there were at least 3 updates being done. But one day I wondered about the performance of each method. Let's see if one is slower than …


Continue reading