Skip to content

Commit

Permalink
Utils: Add function to print PrettyTable objects
Browse files Browse the repository at this point in the history
Add function to print PrettyTable tables that also takes care of
inserting leading and trailing new lines.
  • Loading branch information
tacgomes committed Sep 12, 2024
1 parent 0132622 commit ff51bb2
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 13 deletions.
3 changes: 0 additions & 3 deletions src/investir/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,6 @@ def abort(message: str) -> None:
except InvestirError as ex:
abort(str(ex))

if config.log_level != logging.CRITICAL:
print()

return tr_hist, tax_calculator


Expand Down
10 changes: 5 additions & 5 deletions src/investir/taxcalculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from .typing import ISIN, Ticker, Year
from .transaction import Order, Acquisition, Disposal
from .trhistory import TrHistory
from .utils import raise_or_warn
from .utils import raise_or_warn, printtable

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -103,7 +103,7 @@ def holding(self, isin: ISIN) -> Section104Holding | None:
self._calculate_capital_gains()
return self._holdings.get(isin)

def show_capital_gains(
def show_capital_gains( # pylint: disable=too-many-locals
self,
tax_year_filter: Year | None,
ticker_filter: Ticker | None,
Expand All @@ -119,7 +119,7 @@ def show_capital_gains(
else:
tax_years = sorted(self._capital_gains.keys())

for tax_year in tax_years:
for tax_year_idx, tax_year in enumerate(tax_years, 1):
table = prettytable.PrettyTable(
title=f"Tax year {tax_year}-{tax_year + 1}",
field_names=(
Expand Down Expand Up @@ -169,7 +169,7 @@ def show_capital_gains(
else:
total_losses += abs(cg.gain_loss)

print(table)
printtable(table, leading_newline=tax_year_idx == 1, trailing_newline=False)

def gbp(amount):
return "£" + f"{amount:.2f}"
Expand Down Expand Up @@ -233,7 +233,7 @@ def show_holdings(self, ticker_filter: Ticker | None):

table.add_row(["", "", total_cost, "", "", ""])

print(table, "\n")
printtable(table)

def _calculate_capital_gains(self) -> None:
if self._capital_gains or self._holdings:
Expand Down
10 changes: 5 additions & 5 deletions src/investir/trhistory.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from .transaction import Transaction, Order, Acquisition, Dividend, Transfer, Interest
from .typing import ISIN, Ticker
from .utils import multifilter
from .utils import multifilter, printtable


T = TypeVar("T", bound=Transaction)
Expand Down Expand Up @@ -134,7 +134,7 @@ def show_orders(self, filters: Sequence[Callable] | None = None) -> None:
]
)

print(table, "\n")
printtable(table)

def show_dividends(self, filters: Sequence[Callable] | None = None) -> None:
table = prettytable.PrettyTable(
Expand Down Expand Up @@ -173,7 +173,7 @@ def show_dividends(self, filters: Sequence[Callable] | None = None) -> None:

table.add_row(["", "", "", "", total_paid, total_withheld])

print(table, "\n")
printtable(table)

def show_transfers(self, filters: Sequence[Callable] | None = None) -> None:
table = prettytable.PrettyTable(
Expand Down Expand Up @@ -203,7 +203,7 @@ def show_transfers(self, filters: Sequence[Callable] | None = None) -> None:

table.add_row(["", total_deposited, total_withdrew])

print(table, "\n")
printtable(table)

def show_interest(self, filters: Sequence[Callable] | None = None) -> None:
table = prettytable.PrettyTable(field_names=("Date", "Amount (£)"))
Expand All @@ -224,7 +224,7 @@ def show_interest(self, filters: Sequence[Callable] | None = None) -> None:

table.add_row(["", total_interest])

print(table, "\n")
printtable(table)

def _securities_map(self) -> Mapping[ISIN, Security]:
if not self._securities:
Expand Down
16 changes: 16 additions & 0 deletions src/investir/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from decimal import Decimal
from typing import Final

from prettytable import PrettyTable

from .config import config
from .typing import Year

Expand Down Expand Up @@ -44,3 +46,17 @@ def read_decimal(val: str, default: Decimal = Decimal("0.0")) -> Decimal:

def dict2str(d: Mapping[str, str]) -> str:
return str({k: v for k, v in d.items() if v.strip()})


def printtable(
table: PrettyTable, leading_newline: bool = True, trailing_newline: bool = True
) -> None:
preamble = epilog = ""

if leading_newline and config.log_level != logging.CRITICAL:
preamble = "\n"

if trailing_newline:
epilog = "\n"

print(preamble, table, epilog, sep="")

0 comments on commit ff51bb2

Please sign in to comment.