Python Assignment of Variables in Method Calls


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.


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")

Answered By – Amadan

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published