0

What is the purpose, benefit, or idea behind assigning a variable in a method call?

For example, a method with the following signature:

def get_version(self, workspace):

Can be called like this:

fgdbversion_id = repos.get_version(workspace=test_workspace)

Obviously this sets the workspace parameter to test_workspace, but why not just send get_version(test_workspace). Wouldn't that achieve the same thing? I assume not, otherwise why would this be done. If the assignment was on the method side, it would be a default value, but I don't get it on the call side.

I tried googling this in so many different ways, but I can't find anything on it.

Thank you in advance.

2 Answers 2

6

It is not assignment of variables, but rather specification of a keyword argument (as opposed to a positional argument, which is what you are used to). In this way you are allowed to set arguments out of order, or skip some optional parameters.

For example, the builtin function open is declared this way (or rather, it would be, if it was actually written in Python):

def open(file, mode='r', buffering=-1, encoding=None,
         errors=None, newline=None, closefd=True, opener=None):

If you want to open "output.txt" with mode "w", you can say

open("output.txt", "w")

but also

open(file="output.txt", mode="w")

or even

open(mode="w", file="output.txt")

So far this does not seem all that useful. But what if you want to specify encoding, but don't care about buffering? You could do this:

open("output.txt", "w", -1, "utf-8")

but then you need to know exactly what the default value of buffering is. Would it not be easier to be able to somehow... skip it?

open("output.txt", "w", encoding="utf-8")
5
  • 2
    Also worth adding that using keyword arguments often improves readability, e.g. someone not too familiar with the signature of the open function would have a hard time figuring out what the -1 is for upon reading open("output.txt", "w", -1, "utf-8") without consulting the documentation.
    – blhsing
    Jun 10, 2022 at 1:14
  • 1
    @blhsing Absolutely correct. In fact, I have used open many, many times and yet today, when I went to construct this example, is the first time I ever saw buffering is there (though I obviously knew open had many arguments and would be a good candidate for this example). If I saw open("output.txt", "w", -1, "utf-8") in code, I would absolutely need to look up the documentation.
    – Amadan
    Jun 10, 2022 at 1:20
  • 2
    Even the documentation doesn't explain the -1 :-) Jun 10, 2022 at 1:22
  • 1
    The method in the question only has one parameter (other than self), so these arguments don't make that much sense there... My guess is that it was done for consistency / some style guide. Jun 10, 2022 at 1:25
  • @KellyBundy Fair. It is a bit verbose and redundant when the function only has one argument (though obviously not wrong, per se). I was mainly answering the literal question of "what is it" and not the possibly implied question "what is it doing here".
    – Amadan
    Jun 10, 2022 at 1:27
0

It lets you decide which parameter you want to pass regardless of the order it appears on the function declaration or of how many other there are (assuming they have default values).

When you call a function with multiple parameters, normally, it will take said parameters on the same order they were declared. Specifying which parameter you are trying to pass allow you to ignore that order and pass any parameter in any position.

For instance, let's say we have a simple function that returns the current process id formatted and it simply takes a prefix and a suffix and puts the process id on the middle:

import os


def format_pid(prefix="", suffix=""):
     return f"{prefix}{os.getpid()}{suffix}"

Now, if I call that function like this:

print(format_pid(" before ", " after "))

It works like you would expect and outputs this:

 before 458496 after 

But if I specify the parameters I want to use, I can actually make it take the parameters in reverse order:

print(format_pid(suffix=" before ", prefix=" after "))

Output:

 after 458496 before 

But the true usefulness of it comes when you have function that can take multiple parameters, but you only want to pass one. For instance, if I do:

print(format_pid(" -- "))

It automatically considers that parameter as being the prefix:

 -- 458496

But if I want it to be the suffix, I can do this:

print(format_pid(suffix=" -- "))

Output:

458496 -- 

It may seem trivial, but this is actually a lifesaver when it comes to functions that take many parameters but are usually called with only a few of them or when you have a funtion that takes a variable amount of inputs but you still want to put some optional ones at the end (at the beginning it would force the user to pass them every single time).

A good example for this is the good old print funcion. Look at its declaration:

print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file:  a file-like object (stream); defaults to the current sys.stdout.
sep:   string inserted between values, default a space.
end:   string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

It has four optional parameters that we barely worry about, except for more specific situations where we actually want to change them, in which case we specify one on the function calling:

print("I am fine", "What about you", sep=". ", end="?\n")

Output:

I am fine. What about you?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.