DEV Community

Vruttant Balde
Vruttant Balde

Posted on

Passing Mutables as Function Parameters in Python

In Python it is comparatively very easy to create functions, meaning there are no return types or I should say no types at all!

Okay, So some of you might say that no type hinting is still a thing but I'm going to deny the fact and say that..

The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.

A funny meme on python type hints

They do certainly help for writing clean and understandable code.

Anyway coming on the topic in hand, Have you ever tried passing a mutable object to a function as a parameter and manipulating it afterwards? No? Because you cannot at least as a positional argument. It won't just run and it doesn't make much sense either.

def pos_func([]):
    pass
Enter fullscreen mode Exit fullscreen mode

Ok so how do we access the passed list now? You get it.
Now, if we passed a list as a keyword argument then accessing it is not a big deal, But manipulating it is.

def keyword_func(num, array=[]):
    array.append(num)
    return array

print(keyword_func(1))
print(keyword_func(2))
print(keyword_func(3))
Enter fullscreen mode Exit fullscreen mode

You would expect the output will be the following

[1]
[2]
[3]
Enter fullscreen mode Exit fullscreen mode

But no, the actual output is

[1]
[1, 2]
[1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

The reason is

The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes.

If you don't want this behaviour and don't want the default to be shared between subsequent calls, you can write the function like this instead:

def keyword_func(num, array=None):
    if array is None:
        array = [] 
    array.append(num)
    return array
Enter fullscreen mode Exit fullscreen mode

That's how you pass a mutable object to a function if you don't want the object to be shared between every call.

This was my first blog here at dev.to. Feel free to comment anything you feel about this blog. Next blog would be related to positional arguments, keyword arguments, using them together and how they are separated. Thank you!

Credits:
Type hinting Quote
Type hinting Meme
Reference and Examples

Top comments (0)