Using Keyword Arguments

Python's argument-handling abilities are very versatile. So far we have provided parameters using positional syntax. For example, the first parameter we gave to our frange() function always went to arg0, the second to arg1, and the third to arg2. We have also used default arguments so that some arguments could be omitted. But what happens if we want to pass, say, the first and third arguments, but accept the default second argument? In the next example, we will see how we can achieve this.

Python provides a strip() method for stripping whitespace (or other unwanted characters) from the ends of a string, but it does not provide a function for cleaning up the whitespace inside a string; something that we often need to do when we get strings from users. Here is a function that strips whitespace from both ends of a string and replaces each sequence of internal whitespace with a single space:

Importing

Objects sidebar

Experimenting with Functions in Files

Both frange() and a generator version, gfrange(), are in the file chap02/ frange.py. If we want to try these or any other functions interactively, we can start up IDLE, and append the path where the file we want to use is located to the paths it searches; for example:

>>> sys.path.append("C:/pyqt/chap02") Now the relevant module can be loaded into IDLE: >>> import frange

The file we wish to import from must have a .py extension, and we must not include the extension in the import statement. Now we can use frange() and gfrange() inside IDLE:

The first name frange is the module name, and within that module we wish to access the frange function, which is why we write frange.frange(). We did the same thing a moment ago, when we imported the sys module and accessed its path list using sys.path.

Although we prefer to use IDLE, it is also possible to directly use the Python interpreter when experimenting interactively. If we simply run the Python executable itself (python.exe, for example) in a console, we will get the familiar >>> prompt and be able to use the interpreter interactively.

def simplify(text, space=" \t\r\n\f", delete=""): result = [] word = "" for char in text:

if char in delete:

continue elif char in space: if word:

result.append(word) word = ""

else:

result.append(word) return " ".join(result)

The function iterates over every character in the text string. If the character is in the delete string (which, by default, is empty), we ignore it. If it is a "space" (i.e., it is in the space string), we append the word we have been building up to our list of words, and set the next word to be empty. Otherwise, we append the character to the word we are building up. At the end, we tack on the last word to our list of words. Finally, we return the list of words as a single string with each word separated by a single space, using the string join() method.*

Now let us look at how we can use the function:

simplify(" this and\n that\t too") # Returns "this and that too"

simplify(" Washington D.C.\n", delete=",;:.") # Returns "Washington DC"

simplify(delete="aeiou", text=" disemvoweled ") # Returns "dsmvwld"

In the first case, we use the default arguments for the space and delete parameters. In the second case, we use Python's keyword argument syntax to specify the third parameter while accepting the default for the second parameter. In the last case, we use keyword syntax for both of the arguments we want to use. Notice that if we use keyword syntax, the order of the keyword arguments is up to us—providing that if we also use positional arguments, these precede the keyword arguments, as the second call shows.

The code we have used for simplify() is not as Pythonic as it could be. For example, we should really store word as a list of characters rather than as a string, and we don't need the space parameter since we could use the string object's isspace() method instead. The file chap02/simplified.py contains the simplify() shown here and a similar function, simplified(), which uses the more Pythonic approach. And as noted earlier, although we usually don't show the docstrings in the book, they are in the files.

Python's argument passing is even more sophisticated than we have shown so far. In addition to named arguments, Python functions can be given signatures that accept a variable number of positional arguments and a variable number of keyword arguments. This is a much more versatile and powerful version of C++'s and Java's variable argument lists, but it is rarely needed, so we will not cover it.

Was this article helpful?

0 0
Tube Jacker

Tube Jacker

Download Tube Jacker And Discover Everything You Need To Know About Jacking Unlimited Traffic From The Video Giant. The drop dead easy way to create winning video campaigns that will FLOOD your website with unstoppable FREE traffic, all on complete and total autopilot. How to exploit a sneaky method of boosting exposure and getting your videos to the top of Google within 72 hours, guaranteed.

Get My Free Ebook


Post a comment