Skip to content

Instantly share code, notes, and snippets.

@aaronj1335
Created May 20, 2024 13:10
Show Gist options
  • Save aaronj1335/f282a97d38d7f01b99af290254f7b468 to your computer and use it in GitHub Desktop.
Save aaronj1335/f282a97d38d7f01b99af290254f7b468 to your computer and use it in GitHub Desktop.
2024-01-01 open Assets:Checking
2024-01-01 open Expenses:Groceries
2024-01-01 * "Groceries"
Expenses:Groceries 10 USD
Assets:Checking
from decimal import Decimal
from io import StringIO
from typing import Sequence
from beancount.core.amount import Amount
from beancount.core.data import Posting, Transaction
from beancount.loader import load_file
from beancount.parser.printer import print_entries
# This has the type error with pyright-1.1.363:
#
# postingtype.py:12:11 - error: Argument of type "None" cannot be assigned to parameter "units" of type "Amount" in function "__new__"
#    "None" is incompatible with "Amount" (reportArgumentType)
#
# But it's not a runtime error.
p = Posting(
account="Expenses:Groceries",
units=None,
cost=None,
price=None,
flag=None,
meta=None,
)
entries, errors, options = load_file('example.beancount')
assert not errors
transaction = entries[2]
checking_posting = transaction.postings[1]
# The text of this transaction in the ledger is:
#
# 2024-01-01 * "Groceries"
# Expenses:Groceries 10 USD
# Assets:Checking
#
# But Beancount's load_file adds the -10 USD to it.
assert checking_posting.account == 'Assets:Checking'
assert checking_posting.units == Amount(Decimal(-10), 'USD')
def entries_to_string(entries: Sequence[Transaction]):
output = StringIO()
print_entries(entries, file=output)
output.seek(0)
return output.read()
# This prints the amount that the Beancount importer added:
#
# 2024-01-01 * "Groceries"
# Expenses:Groceries 10 USD
# Assets:Checking -10 USD
#
print(entries_to_string(entries))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment