Skip to content

Commit

Permalink
many ruff/pyright/etc. improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
wolph committed Jan 6, 2025
1 parent 922dbff commit e27a275
Show file tree
Hide file tree
Showing 12 changed files with 53 additions and 191 deletions.
8 changes: 3 additions & 5 deletions mt940/__about__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
__title__ = 'MT940'
__package_name__ = 'mt-940'
__author__ = 'Rick van Hattem (wolph)'
__description__ = ' '.join(
"""
A library to parse MT940 files and returns smart Python collections for
statistics and manipulation.
""".strip().split()
__description__ = (
'A library to parse MT940 files and returns smart Python collections for '
'statistics and manipulation.'
)
__email__ = '[email protected]'
__version__ = '4.30.0'
Expand Down
3 changes: 1 addition & 2 deletions mt940/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@

from . import models, parser, processors, tags, utils
from . import json, models, parser, processors, tags, utils
from .json import JSONEncoder

parse = parser.parse
Expand Down
133 changes: 0 additions & 133 deletions mt940/_compat.py

This file was deleted.

23 changes: 12 additions & 11 deletions mt940/json.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import datetime
import decimal
import json
from typing import Any

from . import models


class JSONEncoder(json.JSONEncoder):
def default(self, value):
def default(self, o: Any) -> Any:
# The following types should simply be cast to strings
str_types = (
datetime.date,
Expand All @@ -22,25 +23,25 @@ def default(self, value):
)

# Handle native types that should be converted to strings
if isinstance(value, str_types):
return str(value)
if isinstance(o, str_types):
return str(o)

# Handling of the Transaction objects to include the actual
# transactions
elif isinstance(value, models.Transactions):
data = value.data.copy()
data['transactions'] = value.transactions
elif isinstance(o, models.Transactions):
data = o.data.copy()
data['transactions'] = o.transactions
return data

# If an object has a `data` attribute, return that instead of the
# `__dict__` ro prevent loops
elif hasattr(value, 'data'):
return value.data
elif hasattr(o, 'data'):
return o.data

# Handle types that have a `__dict__` containing the data (doesn't work
# for classes using `__slots__` such as `datetime`)
elif isinstance(value, dict_types):
return value.__dict__
elif isinstance(o, dict_types):
return o.__dict__

else: # pragma: no cover
return json.JSONEncoder.default(self, value)
return super().default(o)
19 changes: 15 additions & 4 deletions mt940/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

import mt940

from . import _compat, processors
from . import processors


class Model:
Expand Down Expand Up @@ -391,7 +391,9 @@ def sanitize_tag_id_matches(self, matches):
tag_id = self.normalize_tag_id(match.group('tag'))

# tag should be known
assert tag_id in self.tags, f'Unknown tag {tag_id!r} ' f'in line: {match.group(0)!r}'
assert tag_id in self.tags, (
f'Unknown tag {tag_id!r} ' f'in line: {match.group(0)!r}'
)

# special treatment for long tag content with possible
# bad line wrap which produces tag_id like line beginnings
Expand Down Expand Up @@ -487,7 +489,7 @@ def parse(self, data):
# Combine multiple results together as one string, Rabobank has
# multiple :86: tags for a single transaction

for k, v in _compat.iteritems(result):
for k, v in result.items():
if k in transaction.data and hasattr(v, 'strip'):
transaction.data[k] += f'\n{v.strip()}'
else:
Expand All @@ -509,7 +511,7 @@ def __repr__(self):
self.__class__.__name__,
']['.join(
'{}: {}'.format(k.replace('_balance', ''), v)
for k, v in _compat.iteritems(self.data)
for k, v in self.data.items()
if k.endswith('balance')
),
)
Expand All @@ -531,3 +533,12 @@ def __repr__(self):
self.data.get('date'),
self.data.get('amount'),
)


class TransactionsAndTransaction(Transactions, Transaction):
"""
Subclass of both Transactions and Transaction for scope definitions.
This is useful for the non-swift data for example which can function both
as details for a transaction and for a collection of transactions.
"""
16 changes: 11 additions & 5 deletions mt940/parser.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""
Format
---------------------
Expand All @@ -14,7 +13,6 @@
- `Rabobank MT940`_
::
[] = optional
! = fixed length
a = Text
Expand All @@ -25,12 +23,20 @@
n = Numeric
"""

from __future__ import annotations

import os
from typing import Any

import mt940


def parse(src, encoding=None, processors=None, tags=None):
def parse(
src: Any,
encoding: str | None = None,
processors: dict[str, list[Any]] | None = None,
tags: dict[Any, Any] | None = None,
) -> mt940.models.Transactions:
"""
Parses mt940 data and returns transactions object
Expand All @@ -39,9 +45,9 @@ def parse(src, encoding=None, processors=None, tags=None):
:rtype: Transactions
"""

def safe_is_file(filename):
def safe_is_file(filename: Any) -> bool:
try:
return os.path.isfile(src)
return os.path.isfile(filename)
except ValueError: # pragma: no cover
return False

Expand Down
2 changes: 1 addition & 1 deletion mt940/processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ def _parse_mt940_details(detail_str, space=False):
def _parse_mt940_gvcodes(purpose):
result = {}

for key, value in GVC_KEYS.items():
for value in GVC_KEYS.values():
result[value] = None

tmp = {}
Expand Down
19 changes: 2 additions & 17 deletions mt940/tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,23 +72,10 @@
n = Numeric
"""


import enum
import logging
import re

try:
import enum
except ImportError: # pragma: no cover


class enum:
@staticmethod
def unique(*args, **kwargs):
return []

Enum = object


from . import models

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -264,9 +251,7 @@ class NonSwift(Tag):
Pattern: `2!n35x | *x`
"""

class scope(models.Transaction, models.Transactions):
pass

scope = models.TransactionsAndTransaction
id = 'NS'

pattern = r"""
Expand Down
7 changes: 4 additions & 3 deletions mt940/utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import enum
from typing import Any, Optional


def coalesce(*args):
def coalesce(*args: Any) -> Optional[Any]:
"""
Return the first non-None argument
Expand All @@ -26,11 +27,11 @@ class Strip(enum.IntEnum):
BOTH = 3


def join_lines(string, strip=Strip.BOTH):
def join_lines(string: str, strip: Strip = Strip.BOTH) -> str:
"""
Join strings together and strip whitespace in between if needed
"""
lines = []
lines: list[str] = []

for line in string.splitlines():
if strip & Strip.RIGHT:
Expand Down
Loading

0 comments on commit e27a275

Please sign in to comment.