Skip to content

Commit

Permalink
MAINT: Add type annotations
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinThoma committed Jun 22, 2020
1 parent 9088216 commit e580733
Show file tree
Hide file tree
Showing 5 changed files with 119 additions and 112 deletions.
1 change: 1 addition & 0 deletions mpu/datastructures/trie/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ class AbstractTrie(Collection):
@abstractmethod
def autocomplete(self, prefix: str) -> List[str]:
"""Return a list of all words with the given prefix."""
return []
4 changes: 3 additions & 1 deletion mpu/datastructures/trie/string_trie.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ def __init__(self, value, is_word=False, count=0, children=None, freeze=False):
self.count = count
self.is_frozen = freeze

def get_subtrie(self, search_prefix: str, current_trie_node_prefix: str = ""):
def get_subtrie(
self, search_prefix: str, current_trie_node_prefix: str = ""
) -> Tuple[str, "TrieNode"]:
"""
Get the TrieNodes which represents the given prefix.
Expand Down
2 changes: 1 addition & 1 deletion mpu/pd.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def _get_column_info(df: pd.DataFrame, dtype: Dict[str, str]) -> Tuple[Dict, Dic
integer_types = ["int64", "uint8"]
time_types = ["datetime64[ns]"]
other_types = ["object", "category"]
column_info_meta : Dict[str, Dict[str, Any]] = {}
column_info_meta: Dict[str, Dict[str, Any]] = {}
for column_name in df:
column_info_meta[column_name] = {}
counter_obj = df[column_name].value_counts()
Expand Down
197 changes: 99 additions & 98 deletions mpu/units/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,111 @@
import csv
import fractions
from functools import total_ordering
from typing import Tuple, Union

# Third party
import pkg_resources


class Currency:
"""Currency base class which contains information similar to ISO 4217."""

def __init__(
self,
name,
code,
numeric_code,
symbol,
exponent,
entities,
withdrawal_date,
subunits,
):
if not isinstance(name, str):
raise ValueError(
"A currencies name has to be of type str, but "
"was: {}".format(type(name))
)
if not isinstance(code, str):
raise ValueError(
"A currencies code has to be of type str, but "
"was: {}".format(type(code))
)
if not isinstance(exponent, (type(None), int)):
raise ValueError(
"A currencies exponent has to be of type None "
"or int, but was: {}".format(type(code))
)

self.name = name
self.code = code
self.numeric_code = numeric_code
self.symbol = symbol
self.exponent = exponent
self.entities = entities
self.withdrawal_date = withdrawal_date
self.subunits = subunits

def __eq__(self, other):
if isinstance(other, self.__class__):
return self.numeric_code == other.numeric_code
else:
return False

def __ne__(self, other):
return not self.__eq__(other)

def __str__(self):
return self.name

def __repr__(self):
return (
"Currency(name={name}, code={code}, "
"numeric_code={numeric_code})".format(
name=self.name, code=self.code, numeric_code=self.numeric_code
)
)

def __json__(self):
"""Return a JSON-serializable object."""
return {
"name": self.name,
"code": self.code,
"numeric_code": self.numeric_code,
"symbol": self.symbol,
"exponent": self.exponent,
"entities": self.entities,
"withdrawal_date": self.withdrawal_date,
"subunits": self.subunits,
"__python__": "mpu.units:Currency.from_json",
}

for_json = __json__

@classmethod
def from_json(cls, json):
"""Create a Currency object from a JSON dump."""
obj = cls(
name=json["name"],
code=json["code"],
numeric_code=json["numeric_code"],
symbol=json["symbol"],
exponent=json["exponent"],
entities=json["entities"],
withdrawal_date=json["withdrawal_date"],
subunits=json["subunits"],
)
return obj


@total_ordering
class Money:
"""
Unit of account.
Parameters
----------
value : str, Fraction or int
value : Union[str, fractions.Fraction, int, Tuple]
currency : Currency or str
Examples
Expand All @@ -37,7 +129,11 @@ class Money:
'500.00 USD'
"""

def __init__(self, value, currency):
def __init__(
self,
value: Union[str, fractions.Fraction, int, Tuple],
currency: Union[str, Currency],
):
# Handle value
if isinstance(value, tuple):
if len(value) != 2:
Expand All @@ -58,13 +154,9 @@ def __init__(self, value, currency):
self.value = fractions.Fraction(value) # convert to Decimal

# Handle currency
try:
strtype = basestring
except NameError:
strtype = str
if isinstance(currency, Currency):
self.currency = currency
elif isinstance(currency, strtype):
elif isinstance(currency, str):
self.currency = get_currency(currency)
elif currency is None:
self.currency = Currency(
Expand Down Expand Up @@ -300,94 +392,3 @@ def get_currency(currency_str):
subunits=subunits,
)
raise ValueError("Could not find currency '{}'".format(currency_str))


class Currency:
"""Currency base class which contains information similar to ISO 4217."""

def __init__(
self,
name,
code,
numeric_code,
symbol,
exponent,
entities,
withdrawal_date,
subunits,
):
if not isinstance(name, str):
raise ValueError(
"A currencies name has to be of type str, but "
"was: {}".format(type(name))
)
if not isinstance(code, str):
raise ValueError(
"A currencies code has to be of type str, but "
"was: {}".format(type(code))
)
if not isinstance(exponent, (type(None), int)):
raise ValueError(
"A currencies exponent has to be of type None "
"or int, but was: {}".format(type(code))
)

self.name = name
self.code = code
self.numeric_code = numeric_code
self.symbol = symbol
self.exponent = exponent
self.entities = entities
self.withdrawal_date = withdrawal_date
self.subunits = subunits

def __eq__(self, other):
if isinstance(other, self.__class__):
return self.numeric_code == other.numeric_code
else:
return False

def __ne__(self, other):
return not self.__eq__(other)

def __str__(self):
return self.name

def __repr__(self):
return (
"Currency(name={name}, code={code}, "
"numeric_code={numeric_code})".format(
name=self.name, code=self.code, numeric_code=self.numeric_code
)
)

def __json__(self):
"""Return a JSON-serializable object."""
return {
"name": self.name,
"code": self.code,
"numeric_code": self.numeric_code,
"symbol": self.symbol,
"exponent": self.exponent,
"entities": self.entities,
"withdrawal_date": self.withdrawal_date,
"subunits": self.subunits,
"__python__": "mpu.units:Currency.from_json",
}

for_json = __json__

@classmethod
def from_json(cls, json):
"""Create a Currency object from a JSON dump."""
obj = cls(
name=json["name"],
code=json["code"],
numeric_code=json["numeric_code"],
symbol=json["symbol"],
exponent=json["exponent"],
entities=json["entities"],
withdrawal_date=json["withdrawal_date"],
subunits=json["subunits"],
)
return obj
27 changes: 15 additions & 12 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,22 @@ url = https://github.com/MartinThoma/mpu
download_url = https://github.com/MartinThoma/mpu

license = MIT

# https://pypi.org/pypi?%3Aaction=list_classifiers
classifiers =
Development Status :: 3 - Alpha
Environment :: Console
Intended Audience :: Developers
Intended Audience :: Information Technology
License :: OSI Approved :: MIT License
Natural Language :: English
Programming Language :: Python :: 3 :: Only
Programming Language :: Python :: 3.6
Programming Language :: Python :: 3.7
Programming Language :: Python :: 3.8
Topic :: Software Development
Topic :: Utilities
Development Status :: 3 - Alpha
Environment :: Console
Intended Audience :: Developers
Intended Audience :: Information Technology
License :: OSI Approved :: MIT License
Natural Language :: English
Programming Language :: Python :: 3
Programming Language :: Python :: 3 :: Only
Programming Language :: Python :: 3.6
Programming Language :: Python :: 3.7
Programming Language :: Python :: 3.8
Topic :: Software Development
Topic :: Utilities

[options]
packages = find:
Expand Down

0 comments on commit e580733

Please sign in to comment.