This page contains an overview of conventions used in this website.
Code examples and command-line interactions are provided with syntax-highlighting and line numbers.
1 2 3 | (defn add-it-up
[&args]
(apply + args))
|
$ mkdir -p ~/newdir
$ touch ~/newdir/newfile
$ rm -rf ~/newdir
$ echo $HOME
/home/jj
$ sudo su
# whoami
root
Note how we differentiate doing something as root and as a regular user by changing the prompt from $
to #
.
Where applicable, each example is discussed in great detail below it - these explanations are hidden by default so as not to distract from the flow of the article, when such discussion would be a distraction:
1 2 3 4 5 | def some_function(arg1, arg2, **kwargs):
print(arg1)
print(arg2)
for key in kwargs:
print("%s: %s" % (key, kwargs[key]))
|
Standard python function definition. The first two arguments arg1
and arg2
are positional arguments. They do not have default values, so they must be specified, and in the given order.
The special form **kwargs
collects any given keyword arguments into a dictionary.
arg1
and arg2
to standard out (STDOUT). Note that this is using the Python 3 form of the print statement. To use this code in recent versions of python 2, you must add from __future__ import print_function
at the top of your script.kwargs
dictionary, setting the name of the key to a string variable called key
.kwargs
dictionary. Here we are combining the two values into a single string, separated by a colon, using string interpolation. The special %s
tokens are place holders for the values passed in the tuple that follows the interpolation character (%
). The s
is significant, in that python will cast the value to a string before interpolating it.Example
>>> def some_function(arg1, arg2, **kwargs):
... print(arg1)
... print(arg2)
... for key in kwargs:
... print("%s: %s" % (key, kwargs[key]))
...
>>> some_function("boo")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: some_function() missing 1 required positional argument: 'arg2'
>>> some_function("boo", "foo")
boo
foo
>>> some_function("boo", "foo", kw1="value 1", kw4="value 5")
boo
foo
kw4: value 5
kw1: value 1
You can click on the book icon to show an explanation. Clicking on the open book icon will close it.