github soundcloud
python-mode

These are my Python snippets that I use in Emacs with the excellent yankpad by Erik Sjöstrand (Kungsgeten). You are reading this page thanks to Emacs, hugo, ox-hugo and of course yankpad.

Variables like $1, $2, and $0 are tab stop fields.

Some good sources:

Being myself a remarkably stupid fellow, I have had to unteach myself the difficulties, and now beg to present to my fellow fools the parts that are not hard. Master these thoroughly, and the rest will follow. What one fool can do, another can.

Click

This is just the quickstart example from the docs.

import click

$0
@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name',
              help='The person to greet.')
def hello(count, name):
    """Simple program that greets NAME for a total of COUNT times."""
    for x in range(count):
        click.echo('Hello %s!' % name)

if __name__ == '__main__':
    hello()

Click files

Read about arguments here.

The last argument is the destination.

import click


@click.command()
@click.argument('src', nargs=-1)
@click.argument('dst', nargs=1)
def copy(src, dst):
    """Move file SRC to DST."""
    for fn in src:
        click.echo('move %s to folder %s' % (fn, dst))

I may use this:

  • @click.argument('input', type=click.Path(readable=True, dir_okay=False))
  • @click.argument('output', type=click.Path(writable=True, dir_okay=False))

Format string

"{} hehe {}".format($1, $2)

This type of string formatting should not be used with logging. You should also consider using f-strings (f"hi there {name}")

Main

if __name__ == '__main__':
    main()

Dict

Creating a dictionary requires some special characters that are annoying to type and require key chording. You have to spend time moving around too.

It’s better to have a snippet that have a lot of items that you might not use, because it’s much easier to delete items than it is to create them.

$1 = {
    "$2": $3
    "$4": $5
    "$6": $7
    "$8": $9
    "$10": $11
    "$12": $13
    "$14": $15
}

List

$1 = ["$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9", "$10"]

Dict from keys

Suppose you have a list of items, and you want a dictionary with these items as the keys. Use fromkeys:

items = ['a', 'b', 'c', 'd']
idict = dict().fromkeys(items, 0)
idict

StringIO

StringIO gives you file-like access to strings. It’s useful when you are using APIs that only talk to files - for example the csv module.

f = io.StringIO(initial_value='')

f.write("Something")

print(f.getvalue(), end='')

Zip

Imagine we have these two lists:

  • [47, 48, 41]
  • ["Norway", "Sweden", "Switzerland"]

We want to group the elements together pairwise.

zip gives us a list with tuples for every item that share the same position (country_codes[0] and countries[0] go together and so on):

country_codes = [47, 48, 41]
countries = ["Norway", "Sweden", "Switzerland"]
together = zip(country_codes, countries)

print(list(together))
[(47, 'Norway'), (48, 'Sweden'), (41, 'Switzerland')]

So we can loop through the list of tuples. Since zip is an iterator, together will end up empty.

for code, country in together:
    print(code, country)
47 Norway
48 Sweden
41 Switzerland

We can also make a dict, which is super cool (source):

as_dict = dict(zip(country_codes, countries))
print(as_dict)
{47: 'Norway', 48: 'Sweden', 41: 'Switzerland'}