beancount.utils

Generic utility packages and functions.

beancount.utils.bisect_key

A version of bisect that accepts a custom key function, like the sorting ones do.

beancount.utils.bisect_key.bisect_left_with_key(sequence, value, key=None)

Find the last element before the given value in a sorted list.

Parameters
  • sequence – A sorted sequence of elements.

  • value – The value to search for.

  • key – An optional function used to extract the value from the elements of sequence.

Returns

Return the index. May return None.

beancount.utils.bisect_key.bisect_right_with_key(a, x, key, lo=0, hi=None)

Like bisect.bisect_right, but with a key lookup parameter.

Parameters
  • a – The list to search in.

  • x – The element to search for.

  • key – A function, to extract the value from the list.

  • lo – The smallest index to search.

  • hi – The largest index to search.

Returns

As in bisect.bisect_right, an element from list ‘a’.

beancount.utils.csv_utils

Utilities for reading and writing CSV files.

beancount.utils.csv_utils.as_rows(string)

Split a string as rows of a CSV file.

Parameters

string – A string to be split, the contents of a CSV file.

Returns

Lists of lists of strings.

beancount.utils.csv_utils.csv_clean_header(header_row)

Create a new class for the following rows from the header line. This both normalizes the header line and assign

Parameters

header_row – A list of strings, the row with header titles.

Returns

A list of strings, with possibly modified (cleaned) row titles, of the same lengths.

beancount.utils.csv_utils.csv_dict_reader(fileobj, **kw)

Read a CSV file yielding normalized dictionary fields.

This is basically an alternative constructor for csv.DictReader that normalized the field names.

Parameters
  • fileobj – A file object to be read.

  • **kw – Optional arguments forwarded to csv.DictReader.

Returns

A csv.DictReader object.

beancount.utils.csv_utils.csv_split_sections(rows)

Given rows, split them in at empty lines. This is useful for structured CSV files with multiple sections.

Parameters

rows – A list of rows, which are themselves lists of strings.

Returns

A list of sections, which are lists of rows, which are lists of strings.

beancount.utils.csv_utils.csv_split_sections_with_titles(rows)

Given a list of rows, split their sections. If the sections have single column titles, consume those lines as their names and return a mapping of section names.

This is useful for CSV files with multiple sections, where the separator is a title. We use this to separate the multiple tables within the CSV files.

Parameters

rows – A list of rows (list-of-strings).

Returns

A list of lists of rows (list-of-strings).

beancount.utils.csv_utils.csv_tuple_reader(fileobj, **kw)

Read a CSV file yielding namedtuple instances. The CSV file must have a header line.

Parameters
  • fileobj – A file object to be read.

  • **kw – Optional arguments forwarded to csv.DictReader.

Yields

Nametuple instances, one for each row.

beancount.utils.csv_utils.iter_sections(fileobj, separating_predicate=None)

For a given file object, yield file-like objects for each of the sections contained therein. A section is defined as a list of lines that don’t match the predicate. For example, if you want to split by empty lines, provide a predicate that will be true given an empty line, which will cause a new section to be begun.

Parameters
  • fileobj – A file object to read from.

  • separating_predicate – A boolean predicate that is true on separating lines.

Yields

A list of lines that you can use to iterate.

beancount.utils.csv_utils.iter_until_empty(iterator, separating_predicate=None)

An iterator of lines that will stop at the first empty line.

Parameters
  • iterator – An iterator of lines.

  • separating_predicate – A boolean predicate that is true on separating lines.

Yields

Non-empty lines. EOF when we hit an empty line.

beancount.utils.date_utils

Parse the date from various formats.

beancount.utils.date_utils.intimezone(tz_value)

Temporarily reset the value of TZ.

This is used for testing.

Parameters

tz_value (str) – The value of TZ to set for the duration of this context.

Returns

A contextmanager in the given timezone locale.

beancount.utils.date_utils.iter_dates(start_date, end_date)

Yield all the dates between ‘start_date’ and ‘end_date’.

Parameters
  • start_date – An instance of datetime.date.

  • end_date – An instance of datetime.date.

Yields

Instances of datetime.date.

beancount.utils.date_utils.next_month(date)

Compute the date at the beginning of the following month from the given date.

Parameters

date – A datetime.date instance.

Returns

A datetime.date instance, the first day of the month following ‘date’.

beancount.utils.date_utils.parse_date_liberally(string, parse_kwargs_dict=None)

Parse arbitrary strings to dates.

This function is intended to support liberal inputs, so that we can use it in accepting user-specified dates on command-line scripts.

Parameters
  • string – A string to parse.

  • parse_kwargs_dict – Dict of kwargs to pass to dateutil parser.

Returns

A datetime.date object.

beancount.utils.date_utils.render_ofx_date(dtime)

Render a datetime to the OFX format.

Parameters

dtime – A datetime.datetime instance.

Returns

A string, rendered to milliseconds.

beancount.utils.defdict

An instance of collections.defaultdict whose factory accepts a key.

Note: This really ought to be an enhancement to Python itself. I should bother adding this in eventually.

class beancount.utils.defdict.DefaultDictWithKey

A version of defaultdict whose factory accepts the key as an argument. Note: collections.defaultdict would be improved by supporting this directly, this is a common occurence.

class beancount.utils.defdict.ImmutableDictWithDefault(*args, default=None)

An immutable dict which returns a default value for missing keys.

This differs from a defualtdict in that it does not insert a missing default value when one is materialized (from a missing fetch), and furtheremore, the set method is make unavailable to prevent mutation beyond construction.

get(key, _=None)

Return the value for key if key is in the dictionary, else default.

beancount.utils.encryption

Support for encrypted tests.

beancount.utils.encryption.is_encrypted_file(filename)

Return true if the given filename contains an encrypted file.

Parameters

filename – A path string.

Returns

A boolean, true if the file contains an encrypted file.

beancount.utils.encryption.is_gpg_installed()

Return true if GPG 1.4.x or 2.x are installed, which is what we use and support.

beancount.utils.encryption.read_encrypted_file(filename)

Decrypt and read an encrypted file without temporary storage.

Parameters

filename – A string, the path to the encrypted file.

Returns

A string, the contents of the file.

Raises

OSError – If we could not properly decrypt the file.

beancount.utils.file_type

Code that can guess a MIME type for a filename.

This attempts to identify the mim-type of a file suing

  1. The built-in mimetypes library, then

  2. python-magic (if available), and finally

  3. some custom mappers for datatypes used in financial downloads, such as Quicken files.

beancount.utils.file_type.guess_file_type(filename)

Attempt to guess the type of the input file.

Parameters

filename – A string, the name of the file to ugess the type for.

Returns

A suitable mimetype string, or None if we could not guess.

beancount.utils.file_utils

File utilities.

beancount.utils.file_utils.chdir(directory)

Temporarily chdir to the given directory.

Parameters

directory – The directory to switch do.

Returns

A context manager which restores the cwd after running.

beancount.utils.file_utils.find_files(fords, ignore_dirs=('.hg', '.svn', '.git'), ignore_files=('.DS_Store', ))

Enumerate the files under the given directories, stably.

Invalid file or directory names will be logged to the error log.

Parameters
  • fords – A list of strings, file or directory names.

  • ignore_dirs – A list of strings, filenames or directories to be ignored.

Yields

Strings, full filenames from the given roots.

beancount.utils.file_utils.guess_file_format(filename, default=None)

Guess the file format from the filename.

Parameters

filename – A string, the name of the file. This can be None.

Returns

A string, the extension of the format, without a leading period.

beancount.utils.file_utils.path_greedy_split(filename)

Split a path, returning the longest possible extension.

Parameters

filename – A string, the filename to split.

Returns

A pair of basename, extension (which includes the leading period).

beancount.utils.file_utils.touch_file(filename, *otherfiles)

Touch a file and wait until its timestamp has been changed.

Parameters
  • filename – A string path, the name of the file to touch.

  • otherfiles – A list of other files to ensure the timestamp is beyond of.

beancount.utils.import_utils

Utilities for importing symbols programmatically.

beancount.utils.import_utils.import_symbol(dotted_name)

Import a symbol in an arbitrary module.

Parameters

dotted_name – A dotted path to a symbol.

Returns

The object referenced by the given name.

Raises

beancount.utils.invariants

Functions to register auxiliary functions on a class’ methods to check for invariants.

This is intended to be used in a test, whereby your test will setup a class to automatically run invariant verification functions before and after each function call, to ensure some extra sanity checks that wouldn’t be used in non-tests.

Example: Instrument the Inventory class with the check_inventory_invariants() function.

def setUp(module):
instrument_invariants(Inventory,

check_inventory_invariants, check_inventory_invariants)

def tearDown(module):

uninstrument_invariants(Inventory)

beancount.utils.invariants.instrument_invariants(klass, prefun, postfun)

Instrument the class ‘klass’ with pre/post invariant checker functions.

Parameters
  • klass – A class object, whose methods to be instrumented.

  • prefun – A function that checks invariants pre-call.

  • postfun – A function that checks invariants pre-call.

beancount.utils.invariants.invariant_check(method, prefun, postfun)

Decorate a method with the pre/post invariant checkers.

Parameters
  • method – An unbound method to instrument.

  • prefun – A function that checks invariants pre-call.

  • postfun – A function that checks invariants post-call.

Returns

An unbound method, decorated.

beancount.utils.invariants.uninstrument_invariants(klass)

Undo the instrumentation for invariants.

Parameters

klass – A class object, whose methods to be uninstrumented.

beancount.utils.memo

Memoization utilities.

beancount.utils.memo.memoize_recent_fileobj(function, cache_filename, expiration=None)

Memoize recent calls to the given function which returns a file object.

The results of the cache expire after some time.

Parameters
  • function – A callable object.

  • cache_filename – A string, the path to the database file to cache to.

  • expiration – The time during which the results will be kept valid. Use ‘None’ to never expire the cache (this is the default).

Returns

A memoized version of the function.

beancount.utils.memo.now()

Indirection on datetime.datetime.now() for testing.

beancount.utils.misc_utils

Generic utility packages and functions.

class beancount.utils.misc_utils.LineFileProxy(line_writer, prefix=None, write_newlines=False)

A file object that will delegate writing full lines to another logging function. This may be used for writing data to a logging level without having to worry about lines.

close()

Close the line delegator.

flush()

Flush the data to the line writer.

write(data)

Write some string data to the output.

Parameters

data – A string, with or without newlines.

class beancount.utils.misc_utils.TypeComparable

A base class whose equality comparison includes comparing the type of the instance itself.

beancount.utils.misc_utils.box(name=None, file=None)

A context manager that prints out a box around a block. This is useful for printing out stuff from tests in a way that is readable.

Parameters
  • name – A string, the name of the box to use.

  • file – The file object to print to.

Yields

None.

beancount.utils.misc_utils.cmptuple(name, attributes)

Manufacture a comparable namedtuple class, similar to collections.namedtuple.

A comparable named tuple is a tuple which compares to False if contents are equal but the data types are different. We define this to supplement collections.namedtuple because by default a namedtuple disregards the type and we want to make precise comparisons for tests.

Parameters
  • name – The given name of the class.

  • attributes – A string or tuple of strings, with the names of the attributes.

Returns

A new namedtuple-derived type that compares False with other tuples with same contents.

beancount.utils.misc_utils.compute_unique_clean_ids(strings)

Given a sequence of strings, reduce them to corresponding ids without any funny characters and insure that the list of ids is unique. Yields pairs of (id, string) for the result.

Parameters

strings – A list of strings.

Returns

A list of (id, string) pairs.

beancount.utils.misc_utils.deprecated(message)

A decorator generator to mark functions as deprecated and log a warning.

beancount.utils.misc_utils.dictmap(mdict, keyfun=None, valfun=None)

Map a dictionary’s value.

Parameters
  • mdict – A dict.

  • key – A callable to apply to the keys.

  • value – A callable to apply to the values.

beancount.utils.misc_utils.escape_string(string)

Escape quotes and backslashes in payee and narration.

Parameters

string – Any string.

Returns.

The input string, with offending characters replaced.

beancount.utils.misc_utils.filter_type(elist, types)

Filter the given list to yield only instances of the given types.

Parameters
  • elist – A sequence of elements.

  • types – A sequence of types to include in the output list.

Yields

Each element, if it is an instance of ‘types’.

beancount.utils.misc_utils.first_paragraph(docstring)

Return the first sentence of a docstring. The sentence has to be delimited by an empty line.

Parameters

docstring – A doc string.

Returns

A string with just the first sentence on a single line.

beancount.utils.misc_utils.get_screen_height()

Return the height of the terminal that runs this program.

Returns

An integer, the number of characters the screen is high. Return 0 if the terminal cannot be initialized.

beancount.utils.misc_utils.get_screen_width()

Return the width of the terminal that runs this program.

Returns

An integer, the number of characters the screen is wide. Return 0 if the terminal cannot be initialized.

beancount.utils.misc_utils.get_tuple_values(ntuple, predicate, memo=None)

Return all members referred to by this namedtuple instance that satisfy the given predicate. This function also works recursively on its members which are lists or typles, and so it can be used for Transaction instances.

Parameters
  • ntuple – A tuple or namedtuple.

  • predicate – A predicate function that returns true if an attribute is to be output.

  • memo – An optional memoizing dictionary. If a tuple has already been seen, the recursion will be avoided.

Yields

Attributes of the tuple and its sub-elements if the predicate is true.

beancount.utils.misc_utils.groupby(keyfun, elements)

Group the elements as a dict of lists, where the key is computed using the function ‘keyfun’.

Parameters
  • keyfun – A callable, used to obtain the group key from each element.

  • elements – An iterable of the elements to group.

Returns

A dict of key to list of sequences.

beancount.utils.misc_utils.idify(string)

Replace characters objectionable for a filename with underscores.

Parameters

string – Any string.

Returns

The input string, with offending characters replaced.

beancount.utils.misc_utils.import_curses()

Try to import the ‘curses’ module. (This is used here in order to override for tests.)

Returns

The curses module, if it was possible to import it.

Raises

ImportError – If the module could not be imported.

beancount.utils.misc_utils.is_sorted(iterable, key=<function <lambda>>, cmp=<function <lambda>>)

Return true if the sequence is sorted.

Parameters
  • iterable – An iterable sequence.

  • key – A function to extract the quantity by which to sort.

  • cmp – A function that compares two elements of a sequence.

Returns

A boolean, true if the sequence is sorted.

beancount.utils.misc_utils.log_time(operation_name, log_timings, indent=0)

A context manager that times the block and logs it to info level.

Parameters
  • operation_name – A string, a label for the name of the operation.

  • log_timings – A function to write log messages to. If left to None, no timings are written (this becomes a no-op).

  • indent – An integer, the indentation level for the format of the timing line. This is useful if you’re logging timing to a hierarchy of operations.

Yields

The start time of the operation.

beancount.utils.misc_utils.longest(seq)

Return the longest of the given subsequences.

Parameters

seq – An iterable sequence of lists.

Returns

The longest list from the sequence.

beancount.utils.misc_utils.map_namedtuple_attributes(attributes, mapper, object_)

Map the value of the named attributes of object by mapper.

Parameters
  • attributes – A sequence of string, the attribute names to map.

  • mapper – A callable that accepts the value of a field and returns the new value.

  • object_ – Some namedtuple object with attributes on it.

Returns

A new instance of the same namedtuple with the named fields mapped by mapper.

beancount.utils.misc_utils.replace_namedtuple_values(ntuple, predicate, mapper, memo=None)

Recurse through all the members of namedtuples and lists, and for members that match the given predicate, run them through the given mapper.

Parameters
  • ntuple – A namedtuple instance.

  • predicate – A predicate function that returns true if an attribute is to be output.

  • mapper – A callable, that will accept a single argument and return its replacement value.

  • memo – An optional memoizing dictionary. If a tuple has already been seen, the recursion will be avoided.

Yields

Attributes of the tuple and its sub-elements if the predicate is true.

beancount.utils.misc_utils.skipiter(iterable, num_skip)

Skip some elements from an iterator.

Parameters
  • iterable – An iterator.

  • num_skip – The number of elements in the period.

Yields

Elemnets from the iterable, with num_skip elements skipped. For example, skipiter(range(10), 3) yields [0, 3, 6, 9].

beancount.utils.misc_utils.sorted_uniquify(iterable, keyfunc=None, last=False)

Given a sequence of elements, sort and remove duplicates of the given key. Keep either the first or the last (by key) element of a sequence of key-identical elements. This does _not_ maintain the ordering of the original elements, they are returned sorted (by key) instead.

Parameters
  • iterable – An iterable sequence.

  • keyfunc – A function that extracts from the elements the sort key to use and uniquify on. If left unspecified, the identify function is used and the uniquification occurs on the elements themselves.

  • last – A boolean, True if we should keep the last item of the same keys. Otherwise keep the first.

Yields

Elements from the iterable.

beancount.utils.misc_utils.staticvar(varname, initial_value)

Returns a decorator that defines a Python function attribute.

This is used to simulate a static function variable in Python.

Parameters
  • varname – A string, the name of the variable to define.

  • initial_value – The value to initialize the variable to.

Returns

A function decorator.

beancount.utils.misc_utils.swallow(*exception_types)

Catch and ignore certain exceptions.

Parameters

exception_types – A tuple of exception classes to ignore.

Yields

None.

beancount.utils.misc_utils.uniquify(iterable, keyfunc=None, last=False)

Given a sequence of elements, remove duplicates of the given key. Keep either the first or the last element of a sequence of key-identical elements. Order is maintained as much as possible. This does maintain the ordering of the original elements, they are returned in the same order as the original elements.

Parameters
  • iterable – An iterable sequence.

  • keyfunc – A function that extracts from the elements the sort key to use and uniquify on. If left unspecified, the identify function is used and the uniquification occurs on the elements themselves.

  • last – A boolean, True if we should keep the last item of the same keys. Otherwise keep the first.

Yields

Elements from the iterable.

beancount.utils.net_utils

Network utilities.

beancount.utils.net_utils.retrying_urlopen(url, timeout=5, max_retry=5)

Open and download the given URL, retrying if it times out.

Parameters
  • url – A string, the URL to fetch.

  • timeout – A timeout after which to stop waiting for a response and return an error.

  • max_retry – The maximum number of times to retry.

Returns

The contents of the fetched URL.

beancount.utils.pager

Code to write output to a pager.

This module contains an object accumulates lines up to a minimum and then decides whether to flush them to the original output directly if under the threshold (no pager) or creates a pager and flushes the lines to it if above the threshold and then forwards all future lines to it. The purpose of this object is to pipe output to a pager only if the number of lines to be printed exceeds a minimum number of lines.

The contextmanager is intended to be used to pipe output to a pager and wait on the pager to complete before continuing. Simply write to the file object and upon exit we close the file object. This also silences broken pipe errors triggered by the user exiting the sub-process, and recovers from a failing pager command by just using stdout.

class beancount.utils.pager.ConditionalPager(command, minlines=None)

A proxy file for a pager that only creates a pager after a minimum number of lines has been printed to it.

flush_accumulated(file)

Flush the existing lines to the newly created pager. This also disabled the accumulator.

Parameters

file – A file object to flush the accumulated data to.

write(data)

Write the data out. Overridden from the file object interface.

Parameters

data – A string, data to write to the output.

beancount.utils.pager.create_pager(command, file)

Try to create and return a pager subprocess.

Parameters
  • command – A string, the shell command to run as a pager.

  • file – The file object for the pager write to. This is also used as a default if we failed to create the pager subprocess.

Returns

A pair of (file, pipe), a file object and an optional subprocess.Popen instance to wait on. The pipe instance may be set to None if we failed to create a subprocess.

beancount.utils.pager.flush_only(fileobj)

A contextmanager around a file object that does not close the file.

This is used to return a context manager on a file object but not close it. We flush it instead. This is useful in order to provide an alternative to a pager class as above.

Parameters

fileobj – A file object, to remain open after running the context manager.

Yields

A context manager that yields this object.

beancount.utils.regexp_utils

Regular expression helpers.

beancount.utils.regexp_utils.re_replace_unicode(regexp)

Substitute Unicode Properties in regular expressions with their corresponding expanded ranges.

Parameters

regexp – A regular expression string.

Returns

Return the regular expression with Unicode Properties substituted.

beancount.utils.snoop

Text manipulation utilities.

class beancount.utils.snoop.Snoop(maxlen=None)

A snooper callable that just saves the returned values of a function. This is particularly useful for re.match and re.search in conditionals, e.g.:

snoop = Snoop()
...
if snoop(re.match(r"(\d+)-(\d+)-(\d+)", text)):
  year, month, date = snoop.value.group(1, 2, 3)
value

The last value snooped from a function call.

history

If ‘maxlen’ was specified, the last few values that were snooped.

beancount.utils.snoop.snoopify(function)

Decorate a function as snoopable.

This is meant to reassign existing functions to a snoopable version of them. For example, if you wanted ‘re.match’ to be automatically snoopable, just decorate it like this:

re.match = snoopify(re.match)

and then you can just call ‘re.match’ in a conditional and then access ‘re.match.value’ to get to the last returned value.

beancount.utils.test_utils

Support utillities for testing scripts.

class beancount.utils.test_utils.RCall(args, kwargs, return_value)
class beancount.utils.test_utils.TestCase(methodName='runTest')
assertLines(text1, text2, message=None)

Compare the lines of text1 and text2, ignoring whitespace.

Parameters
  • text1 – A string, the expected text.

  • text2 – A string, the actual text.

  • message – An optional string message in case the assertion fails.

Raises

AssertionError – If the exception fails.

assertOutput(expected_text)

Expect text printed to stdout.

Parameters

expected_text – A string, the text that should have been printed to stdout.

Raises

AssertionError – If the text differs.

class beancount.utils.test_utils.TestTempdirMixin
setUp()
tearDown()
beancount.utils.test_utils.call_command(command)

Run the script with a subprocess.

Parameters

script_args – A list of strings, the arguments to the subprocess, including the script name.

Returns

A triplet of (return code integer, stdout ext, stderr text).

beancount.utils.test_utils.capture(*attributes)

A context manager that captures what’s printed to stdout.

Parameters

*attributes – A tuple of strings, the name of the sys attributes to override with StringIO instances.

Yields

A StringIO string accumulator.

beancount.utils.test_utils.create_temporary_files(root, contents_map)

Create a number of temporary files under ‘root’.

This routine is used to initialize the contents of multiple files under a temporary directory.

Parameters
  • root – A string, the name of the directory under which to create the files.

  • contents_map – A dict of relative filenames to their contents. The content strings will be automatically dedented for convenience. In addition, the string ‘ROOT’ in the contents will be automatically replaced by the root directory name.

beancount.utils.test_utils.docfile(function, **kwargs)

A decorator that write the function’s docstring to a temporary file and calls the decorated function with the temporary filename. This is useful for writing tests.

Parameters

function – A function to decorate.

Returns

The decorated function.

beancount.utils.test_utils.docfile_extra(**kwargs)

A decorator identical to @docfile, but it also takes kwargs for the temporaryfile, Kwargs:

e.g. buffering, encoding, newline, dir, prefix, and suffix.

Returns

docfile

beancount.utils.test_utils.environ(varname, newvalue)

A context manager which pushes varname’s value and restores it later.

Parameters
  • varname – A string, the environ variable name.

  • newvalue – A string, the desired value.

beancount.utils.test_utils.find_python_lib()

Return the path to the root of the Python libraries.

Returns

A string, the root directory.

beancount.utils.test_utils.find_repository_root(filename=None)

Return the path to the repository root.

Parameters

filename – A string, the name of a file within the repository.

Returns

A string, the root directory.

beancount.utils.test_utils.make_failing_importer(*removed_module_names)

Make an importer that raise an ImportError for some modules.

Use it like this:

@mock.patch(‘builtins.__import__’, make_failing_importer(‘setuptools’)) def test_

Parameters

removed_module_name – The name of the module import that should raise an exception.

Returns

A decorated test decorator.

beancount.utils.test_utils.nottest(func)

Make the given function not testable.

beancount.utils.test_utils.patch(obj, attributes, replacement_type)

A context manager that temporarily patches an object’s attributes.

All attributes in ‘attributes’ are saved and replaced by new instances of type ‘replacement_type’.

Parameters
  • obj – The object to patch up.

  • attributes – A string or a sequence of strings, the names of attributes to replace.

  • replacement_type – A callable to build replacment objects.

Yields

An instance of a list of sequencs of ‘replacement_type’.

beancount.utils.test_utils.record(fun)

Decorates the function to intercept and record all calls and return values.

Parameters

fun – A callable to be decorated.

Returns

A wrapper function with a .calls attribute, a list of RCall instances.

beancount.utils.test_utils.run_with_args(function, args)

Run the given function with sys.argv set to argv. The first argument is automatically inferred to be where the function object was defined. sys.argv is restored after the function is called.

Parameters
  • function – A function object to call with no arguments.

  • argv – A list of arguments, excluding the script name, to be temporarily set on sys.argv.

Returns

The return value of the function run.

beancount.utils.test_utils.search_words(words, line)

Search for a sequence of words in a line.

Parameters
  • words – A list of strings, the words to look for, or a space-separated string.

  • line – A string, the line to search into.

Returns

A MatchObject, or None.

beancount.utils.test_utils.skipIfRaises(*exc_types)

A context manager (or decorator) that skips a test if an exception is raised.

Parameters

exc_type

Yields

Nothing, for you to execute the function code.

Raises

SkipTest – if the test raised the expected exception.

beancount.utils.test_utils.subprocess_env()

Return a dict to use as environment for running subprocesses.

Returns

A string, the root directory.

beancount.utils.test_utils.tempdir(delete=True, **kw)

A context manager that creates a temporary directory and deletes its contents unconditionally once done.

Parameters
  • delete – A boolean, true if we want to delete the directory after running.

  • **kw – Keyword arguments for mkdtemp.

Yields

A string, the name of the temporary directory created.

beancount.utils.text_utils

Text manipulation utilities.

beancount.utils.text_utils.entitize_ampersand(filename)

Convert unescaped ampersand characters (&) to XML entities.

This is used to fix code that has been programmed by bad developers who didn’t think about escaping the entities in their strings. file does not contain :param filename: A string, the name of the file to convert.

Returns

A self-destructing NamedTemporaryFile object that has been flushed and which you may read to obtain the fixed contents.

beancount.utils.text_utils.replace_number(match)

Replace a single number matched from text into X’es. ‘match’ is a MatchObject from a regular expressions match. (Use this with re.sub()).

Parameters

match – A MatchObject.

Returns

A replacement string, consisting only of X’es.

beancount.utils.text_utils.replace_numbers(text)

Replace all numbers found within text.

Note that this is a heuristic used to filter out private numbers from web pages in incognito mode and thus may not be perfect. It should let through numbers which are part of URLs.

Parameters

text – An input string object.

Returns

A string, with relevant numbers hopefully replaced with X’es.

beancount.utils.version

Implement common options across all programs.

beancount.utils.version.ArgumentParser(*args, **kwargs)

Add a standard –version option to an ArgumentParser.

Parameters
  • *args – Arguments for the parser.

  • *kwargs – Keyword arguments for the parser.

Returns

An instance of ArgumentParser, with our default options set.

beancount.utils.version.compute_version_string(version, changeset, timestamp)

Compute a version string from the changeset and timestamp baked in the parser.

Parameters
  • version – A string, the version number.

  • changeset – A string, a version control string identifying the commit of the version.

  • timestamp – An integer, the UNIX epoch timestamp of the changeset.

Returns

A human-readable string for the version.