Just notes on various things

Fred Damstra 57eabd9a49 Merge branch 'master' of https://io.monkeybox.org/git/fdamstra/python_notes 7 年 前
examples 57eabd9a49 Merge branch 'master' of https://io.monkeybox.org/git/fdamstra/python_notes 7 年 前
.gitignore 1ca81aa725 Initial commit 7 年 前
LICENSE 1ca81aa725 Initial commit 7 年 前
README.md 6a9c17247b Doctest example. 7 年 前

README.md

python_notes

Just notes on various things

docstrings

Use 'em.

doctest

In your docstring, put examples that look like the command-line, such as

def square(x):
    """
    Returns x times itself.
    >>> square(2)
    4
    """
    return x*x

Then import doctest and doctest.testmod() inside __main__, and python will run the tests to verify correctness.

Run with python -v to see the output of the doctest module.

ArgParse

Interesting Tidbits

Redirect stdout to a file. The with isolates context and prevents certain race conditions, handling errors appropriately.

with open('help.txt', 'w') as f:
    with redirect_stdout(f):
        help(pow)

Caching

If you have a function that always returns the same result for a given input, you can cache the result by prefacing with @lru_cache. e.g.

from functools import lru_cache

@lru_cache(maxsize=32)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)