When I first started programming in Python this used to trip me up all the time. Hopefully through my pain I have managed to find a way to convey just how simple this concept is. Show
Working with argsThese functions allow you to extend your function massively, as when you design functions, you don’t want to limit the number of inputs to the function to a certain amount. A good example of args in action is when you are are dealing with statistical functions such as sum and mean. If you built a function, which could only add one number to another, then that would not be as useful as adding a number to an unknown range. This is where args come in. I will demonstrate how args is structured via a simple function and we will deconstruct this function: Okay so what this does is the following:
This is a powerful concept as it means we can pass multiple unnamed arguments of multiple types (string, integer, float) to this function and the logic inside the function would work out what to do with it. Here it is simply printing out the values, but this could be a numerical summary function, as I will implement after this. We then implement our call to this by using the function, which returns the below: First argument is this is my normal argument Passed another argument (*arg_values): additional argument 1 Passed another argument (*arg_values): additional argument 2 Passed another argument (*arg_values): additional argument 3 Essentially, we have found a way to capture the additional arguments passed by our miracle single asterisk. Let’s extend this to sum up numerical values. Extending the args to work with numerical valuesWe will extend what we have practiced in the previous section to look at how we would use args to create a custom sum function. As you have seen – you don’t actually have to name you function inputs *args they can be anything, so long as they are prefixed with an asterisk. This function:
To call this function I simply pass the items I want to add together: # Use the new function print(summer_function(20,40,60,80,100)) What is returned to the console is the following: <class 'tuple'> 300 Simply that is how you can use arguments to extend the power of your functions immediately. The next use case we will look at keyword arguments (**kwargs). What’s kwargs got to do with it?Apologies for the shockingly bad Tina Turner headline on this title. Enough of my ramblings, what are kwargs. Kwargs are passed key work arguments that have a key and a value, much like how you would work with a Python dictionary. Here we will implement a function that deals with multiple arguments and we will pass in a number of values that the function has never seen before: Let’s decompose what this function is doing:
Running the function we get: working_with_kwargs(first_name='Gary', occupation='ML Engineer Lead', fav_food='Fish') This produces: first_name=Gary His name is Gary occupation=ML Engineer Lead fav_food=Fish Item contains his favourite food Fish. Because we can query by key and value we can also use conditional logic to look when there is a match. Ordering arguments in a functionThe correct ordering of arguments in a function is as so:
These need to be specified in this order in every function Unpacking args and kwargsThis can be really powerful. I will show you some examples of unpacking arguments from args and kwargs following. Unpacking argsWe will focus on unpacking arguments firstly, as this allows you to perform operations like merging multiple lists of the same size, or simply just passing a list of values. PyTorch uses kwargs unpacking a lot for passing the dictionary structure of a neural network to the model, so it is useful to start with these examples to get a good grasp of how to unpack our arguments. The first example I will show is how to unpack a list of values and pass these unpacked arguments as seperate parameters into a sum function: What is happening here?
Unpacking args by merging listsLet’s use what we have learned previously to join two lists together, which is another novel way we could work with unpacking arguments. Pardon the pun, but let’s unpack this:
The output of this code is: 30 [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000, 27, 64, 125, 216, 343, 512, 729, 1000, 1331, 1728, 1000, 1331, 1728, 2197, 2744, 3375, 4096, 4913, 5832, 6859] That’s all there is to it. Unpacking kwargsIn this example, we will use the same motivation as we did before in merging lists, but this time we will use kwargs to merge two dictionaries together. Remember that kwargs have an associated key and value to their input parameters, so they work very much like a dictionary in Python. Again, some unpacking required – stop it with the puns!:
{'x1': 10, 'x2': 30, 'x3': 20, 'x4': 32} I tend to use kwarg unpacking a lot when working with PyTorch and Transformer models, as normally you have an external modelling configuration that is a dictionary and you want to pass each one of the parameters into the model – by using model(**my_model_params) it means I do not have to extract them all separately to pass to the model each time. Such a time saver. ClosingI hope you have found this post informative. I thought of coming at it from how I like to learn new concepts. Boiling them down to the simple components I know and then stepping through what each stage is doing. Can a function have multiple arguments in Python?We can pass multiple arguments to a python function by predetermining the formal parameters in the function definition.
Can a function have multiple arguments?Luckily, you can write functions that take in more than one parameter by defining as many parameters as needed, for example: def function_name(data_1, data_2):
How many arguments can a function have in Python?In Python, we can define two types of parameters that have variable lengths. They can be considered special types of optional parameters. In other words, there is no limit to the number of arguments that are passed to the parameter when we call this function.
How do you pass multiple inputs to a function in Python?Using split() method
This function helps in getting multiple inputs from users. It breaks the given input by the specified separator. If a separator is not provided then any white space is a separator. Generally, users use a split() method to split a Python string but one can use it for taking multiple inputs.
|