Skip to content

Commit

Permalink
Get rid of unnecessary "_ClassName" convention
Browse files Browse the repository at this point in the history
Instead, just don't import the classes in the public api, then the user
will also never see them.

Note that we still use the convention for attributes to mark them as
internal to a class.
  • Loading branch information
Splines committed Mar 15, 2024
1 parent d7345cf commit 94209da
Show file tree
Hide file tree
Showing 15 changed files with 110 additions and 113 deletions.
6 changes: 3 additions & 3 deletions src/api/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

@dataclass
# pylint: disable-next=too-many-instance-attributes
class _Config:
class Config:
"""Configuration settings for the application.
Args:
Expand Down Expand Up @@ -90,7 +90,7 @@ def config_init(
) -> None:
global configuration # pylint: disable=global-statement

configuration = _Config(
configuration = Config(
sigfigs,
decimal_places,
print_auto,
Expand All @@ -104,7 +104,7 @@ def config_init(
_check_config()


configuration = cast(_Config, None) # pylint: disable=invalid-name
configuration = cast(Config, None) # pylint: disable=invalid-name
config_init()


Expand Down
4 changes: 2 additions & 2 deletions src/api/console_stringifier.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from domain.result import _Result
from domain.result import Result
from application.stringifier import Stringifier


Expand All @@ -19,7 +19,7 @@ class ConsoleStringifier(Stringifier):
unit_prefix = " "
unit_suffix = ""

def result_to_str(self, result: _Result):
def result_to_str(self, result: Result):
"""
Returns the result as human-readable string.
"""
Expand Down
32 changes: 16 additions & 16 deletions src/api/parsers.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from typing import Union, List, Tuple

from application.helpers import _Helpers
from domain.value import _Value
from domain.uncertainty import _Uncertainty
from application.helpers import Helpers
from domain.value import Value
from domain.uncertainty import Uncertainty


def check_if_number_string(value: str) -> None:
Expand Down Expand Up @@ -58,15 +58,15 @@ def parse_name(name: str) -> str:
# Turn digits into word(s):
word = ""
if num_of_digits <= 3:
word += _Helpers.number_to_word(int(name[:num_of_digits]))
word += Helpers.number_to_word(int(name[:num_of_digits]))
else:
word += _Helpers.number_to_word(int(name[0]))
word += Helpers.number_to_word(int(name[0]))
for i in range(1, num_of_digits):
word += _Helpers.capitalize((_Helpers.number_to_word(int(name[i]))))
word += Helpers.capitalize((Helpers.number_to_word(int(name[i]))))

# Add word to parsed_name:
if parsed_name != "":
word = _Helpers.capitalize(word)
word = Helpers.capitalize(word)
parsed_name += word
next_chat_upper = True

Expand Down Expand Up @@ -130,7 +130,7 @@ def parse_decimal_places(decimal_places: Union[int, None]) -> Union[int, None]:
return decimal_places


def parse_value(value: Union[float, int, str]) -> _Value:
def parse_value(value: Union[float, int, str]) -> Value:
"""Converts the value to a _Value object."""
if not isinstance(value, (float, int, str)):
raise TypeError(f"`value` must be a float, int or string, not {type(value)}")
Expand All @@ -142,10 +142,10 @@ def parse_value(value: Union[float, int, str]) -> _Value:
if isinstance(value, int):
value = float(value)

return _Value(value)
return Value(value)


def parse_exact_value(value: str) -> _Value:
def parse_exact_value(value: str) -> Value:
# Determine min exponent:
exponent_offset = 0
value_str = value
Expand All @@ -158,7 +158,7 @@ def parse_exact_value(value: str) -> _Value:
else:
min_exponent = exponent_offset

return _Value(float(value), min_exponent)
return Value(float(value), min_exponent)


def parse_uncertainties(
Expand All @@ -169,7 +169,7 @@ def parse_uncertainties(
Tuple[Union[float, int, str], str],
List[Union[float, str, Tuple[Union[float, int, str], str]]],
]
) -> List[_Uncertainty]:
) -> List[Uncertainty]:
"""Converts the uncertainties to a list of _Uncertainty objects."""
uncertainties_res = []

Expand All @@ -181,7 +181,7 @@ def parse_uncertainties(

for uncert in uncertainties:
if isinstance(uncert, (float, int, str)):
uncertainties_res.append(_Uncertainty(_parse_uncertainty_value(uncert)))
uncertainties_res.append(Uncertainty(_parse_uncertainty_value(uncert)))

elif isinstance(uncert, Tuple):
if not isinstance(uncert[0], (float, int, str)):
Expand All @@ -190,7 +190,7 @@ def parse_uncertainties(
+ f" int or a string, not {type(uncert[0])}"
)
uncertainties_res.append(
_Uncertainty(_parse_uncertainty_value(uncert[0]), parse_name(uncert[1]))
Uncertainty(_parse_uncertainty_value(uncert[0]), parse_name(uncert[1]))
)

else:
Expand All @@ -201,7 +201,7 @@ def parse_uncertainties(
return uncertainties_res


def _parse_uncertainty_value(value: Union[float, int, str]) -> _Value:
def _parse_uncertainty_value(value: Union[float, int, str]) -> Value:
"""Parses the value of an uncertainty."""

if isinstance(value, str):
Expand All @@ -210,7 +210,7 @@ def _parse_uncertainty_value(value: Union[float, int, str]) -> _Value:
else:
if isinstance(value, int):
value = float(value)
return_value = _Value(value)
return_value = Value(value)

if return_value.get() <= 0:
raise ValueError("Uncertainty must be positive.")
Expand Down
4 changes: 2 additions & 2 deletions src/api/printable_result.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from api.console_stringifier import ConsoleStringifier
import api.config as c
from application.latex_stringifier import LatexStringifier
from domain.result import _Result
from domain.result import Result


class PrintableResult:
def __init__(self, result: _Result):
def __init__(self, result: Result):
self._result = result

def print(self):
Expand Down
12 changes: 6 additions & 6 deletions src/api/res.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
from api.printable_result import PrintableResult
from api import parsers
import api.config as c
from application.cache import _ResultsCache
from application.rounder import _Rounder
from domain.result import _Result
from application.cache import ResultsCache
from application.rounder import Rounder
from domain.result import Result

_res_cache = _ResultsCache()
_res_cache = ResultsCache()


@overload
Expand Down Expand Up @@ -99,10 +99,10 @@ def res(
decimal_places_res = parsers.parse_decimal_places(decimal_places)

# Assemble the result
result = _Result(
result = Result(
name_res, value_res, unit_res, uncertainties_res, sigfigs_res, decimal_places_res
)
_Rounder.round_result(result, c.configuration.to_rounding_config())
Rounder.round_result(result, c.configuration.to_rounding_config())
_res_cache.add(name, result)

printable_result = PrintableResult(result)
Expand Down
10 changes: 5 additions & 5 deletions src/application/cache.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from domain.result import _Result
from domain.result import Result


class _ResultsCache:
class ResultsCache:
"""
A cache for all user-defined results. Results are hashed by their name.
If the user tries to add a result with a name that already exists in the cache,
Expand All @@ -10,10 +10,10 @@ class _ResultsCache:
"""

def __init__(self):
self.cache: dict[str, _Result] = {}
self.cache: dict[str, Result] = {}

def add(self, name, result: _Result):
def add(self, name, result: Result):
self.cache[name] = result

def get_all_results(self) -> list[_Result]:
def get_all_results(self) -> list[Result]:
return list(self.cache.values())
2 changes: 1 addition & 1 deletion src/application/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
}


class _Helpers:
class Helpers:
@classmethod
def get_exponent(cls, value: float) -> int:
return math.floor(math.log10(abs(value)))
Expand Down
18 changes: 9 additions & 9 deletions src/application/latex_stringifier.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from domain.result import _Result
from application.helpers import _Helpers
from domain.result import Result
from application.helpers import Helpers
from application.latex_ifelse import LatexIfElseBuilder
from application.stringifier import Stringifier

Expand Down Expand Up @@ -27,13 +27,13 @@ class LatexStringifier(Stringifier):
unit_prefix = r"\, \unit{"
unit_suffix = "}"

def result_to_latex_cmd(self, result: _Result) -> str:
def result_to_latex_cmd(self, result: Result) -> str:
"""
Returns the result as LaTeX command to be used in a .tex file.
"""
builder = LatexIfElseBuilder()

cmd_name = f"{self.config.identifier}{_Helpers.capitalize(result.name)}"
cmd_name = f"{self.config.identifier}{Helpers.capitalize(result.name)}"
latex_str = rf"\newcommand*{{\{cmd_name}}}[1][]{{" + "\n"

# Default case (full result) & value
Expand All @@ -49,8 +49,8 @@ def result_to_latex_cmd(self, result: _Result) -> str:
if len(result.uncertainties) == 1:
uncertainty_name = "error"
else:
uncertainty_name = u.name if u.name != "" else _Helpers.number_to_word(i + 1)
uncertainty_name = f"error{_Helpers.capitalize(uncertainty_name)}"
uncertainty_name = u.name if u.name != "" else Helpers.number_to_word(i + 1)
uncertainty_name = f"error{Helpers.capitalize(uncertainty_name)}"
error_latex_str = self.create_str(u.uncertainty, [], result.unit)
builder.add_branch(uncertainty_name, error_latex_str)

Expand Down Expand Up @@ -86,19 +86,19 @@ def result_to_latex_cmd(self, result: _Result) -> str:

return latex_str

def result_to_latex_str(self, result: _Result) -> str:
def result_to_latex_str(self, result: Result) -> str:
"""
Returns the result as LaTeX string making use of the siunitx package.
"""
return self.create_str(result.value, result.uncertainties, result.unit)

def result_to_latex_str_value(self, result: _Result) -> str:
def result_to_latex_str_value(self, result: Result) -> str:
"""
Returns only the value as LaTeX string making use of the siunitx package.
"""
return self.create_str(result.value, [], "")

def result_to_latex_str_without_error(self, result: _Result) -> str:
def result_to_latex_str_without_error(self, result: Result) -> str:
"""
Returns the result without error as LaTeX string making use of the siunitx package.
"""
Expand Down
16 changes: 8 additions & 8 deletions src/application/rounder.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from typing import List

from dataclasses import dataclass
from domain.result import _Result
from domain.uncertainty import _Uncertainty
from application.helpers import _Helpers
from domain.result import Result
from domain.uncertainty import Uncertainty
from application.helpers import Helpers


@dataclass
Expand All @@ -14,10 +14,10 @@ class RoundingConfig:
decimal_places_fallback: int


class _Rounder:
class Rounder:

@classmethod
def round_result(cls, result: _Result, config: RoundingConfig) -> None:
def round_result(cls, result: Result, config: RoundingConfig) -> None:
"""
In-place rounds all numerical fields of a result to the correct
number of significant figures.
Expand Down Expand Up @@ -69,7 +69,7 @@ def round_result(cls, result: _Result, config: RoundingConfig) -> None:

@classmethod
# pylint: disable-next=too-many-branches
def _round_result(cls, result: _Result, config: RoundingConfig) -> None:
def _round_result(cls, result: Result, config: RoundingConfig) -> None:
"""See the docstring of the public `round_result` for details."""

value = result.value
Expand Down Expand Up @@ -107,7 +107,7 @@ def _round_result(cls, result: _Result, config: RoundingConfig) -> None:
continue

normalized_value = abs(u.uncertainty.get()) * 10 ** (
-_Helpers.get_exponent(u.uncertainty.get())
-Helpers.get_exponent(u.uncertainty.get())
)

if round(normalized_value, 1) >= 3.0:
Expand All @@ -132,7 +132,7 @@ def _round_result(cls, result: _Result, config: RoundingConfig) -> None:

@classmethod
def _uncertainties_set_min_exponents(
cls, uncertainties: List[_Uncertainty], min_exponent: int
cls, uncertainties: List[Uncertainty], min_exponent: int
) -> None:
for u in uncertainties:
if not u.uncertainty.is_exact():
Expand Down
14 changes: 7 additions & 7 deletions src/application/stringifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
# for why we use a Protocol instead of a ABC class, see
# https://github.com/microsoft/pyright/issues/2601#issuecomment-977053380

from domain.value import _Value
from domain.uncertainty import _Uncertainty
from application.helpers import _Helpers
from domain.value import Value
from domain.uncertainty import Uncertainty
from application.helpers import Helpers


@dataclass
Expand Down Expand Up @@ -45,7 +45,7 @@ class Stringifier(Protocol):
def __init__(self, config: StringifierConfig):
self.config = config

def create_str(self, value: _Value, uncertainties: List[_Uncertainty], unit: str) -> str:
def create_str(self, value: Value, uncertainties: List[Uncertainty], unit: str) -> str:
"""
Returns the result as LaTeX string making use of the siunitx package.
Expand All @@ -68,7 +68,7 @@ def create_str(self, value: _Value, uncertainties: List[_Uncertainty], unit: str
if should_use_parentheses:
latex_str += self.left_parenthesis
latex_str += sign
latex_str += _Helpers.round_to_n_decimal_places(value_normalized, decimal_places)
latex_str += Helpers.round_to_n_decimal_places(value_normalized, decimal_places)

for u in uncertainties:
uncertainty_normalized = u.uncertainty.get_abs() * factor
Expand All @@ -78,7 +78,7 @@ def create_str(self, value: _Value, uncertainties: List[_Uncertainty], unit: str
else u.uncertainty.get_decimal_place()
)
latex_str += self.plus_minus
latex_str += _Helpers.round_to_n_decimal_places(uncertainty_normalized, decimal_places)
latex_str += Helpers.round_to_n_decimal_places(uncertainty_normalized, decimal_places)
if len(uncertainties) > 1:
latex_str += self.error_name_prefix + u.name + self.error_name_suffix

Expand All @@ -94,7 +94,7 @@ def create_str(self, value: _Value, uncertainties: List[_Uncertainty], unit: str
return latex_str

def _should_use_scientific_notation(
self, value: _Value, uncertainties: List[_Uncertainty]
self, value: Value, uncertainties: List[Uncertainty]
) -> bool:
"""
Returns whether scientific notation should be used for the given value and uncertainties.
Expand Down
Loading

0 comments on commit 94209da

Please sign in to comment.