Just notes on various things

Fred Damstra [afs macbook] 19d2b4a0a8 Updates 3 years ago
examples 19d2b4a0a8 Updates 3 years ago
.gitignore a13803c4c0 Cache example. 6 years ago
LICENSE 1ca81aa725 Initial commit 6 years ago
README.md 232348c23d Merged README 6 years ago

README.md

python_notes

Just notes on various things

Naming Notes

Classes use CamelCaps Functions and varibles are lowercase() or lowercase_with_underscores().

Always use self for the first argument to instance methods. Always use cls for the first argument to class methods

Magic Methods

Classes have certain magic methods that help make objects behave in pythonlike ways.

  • __repr__ returns a string representation of the object. Should be unambiguous. (i.e. add parameters).
  • __str__ returns a string representation of the object. Should be easily readable but not necessarily unambiguous. Careful, can be confused with __repr__ in some cases.

Comments

Block comments are at the same indentation and are complete sentences. Inline comments shouldn't state the obvious.

Avoid:

x = x + 1  # Increment x

But this can be useful:

x = x + 1  # Compensate for the border

docstrings

Use 'em. See PEP257 - https://www.python.org/dev/peps/pep-0257

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)