summaryrefslogtreecommitdiff
path: root/pint
diff options
context:
space:
mode:
authorHernan <hernan.grecco@gmail.com>2022-02-12 11:19:56 -0300
committerHernan <hernan.grecco@gmail.com>2022-02-12 19:34:18 -0300
commitfe81a9505cf1f64aabae8dfb2e5e1cdb4faca06b (patch)
treeb72e1744c559ab66c9bab59c75e87cb8f879076f /pint
parent88aa34a7e74937afda6889611a68daa384ac4aa6 (diff)
downloadpint-fe81a9505cf1f64aabae8dfb2e5e1cdb4faca06b.tar.gz
Move ImportDefinition to parser and DefaultDefinition to registry
Diffstat (limited to 'pint')
-rw-r--r--pint/parser.py45
-rw-r--r--pint/registry.py51
2 files changed, 45 insertions, 51 deletions
diff --git a/pint/parser.py b/pint/parser.py
index 9667e16..9e49cf0 100644
--- a/pint/parser.py
+++ b/pint/parser.py
@@ -55,6 +55,19 @@ class DefinitionFile:
return bool(self.errors)
+@dataclass(frozen=True)
+class ImportDefinition:
+ """Definition for the @import directive"""
+
+ path: str
+
+ @classmethod
+ def from_string(
+ cls, definition: str, non_int_type: type = float
+ ) -> ImportDefinition:
+ return ImportDefinition(definition[7:].strip())
+
+
class Parser:
"""Class to parse a definition file into an intermediate object representation.
@@ -72,6 +85,7 @@ class Parser:
self._directives = {}
self._non_int_type = non_int_type
self._raise_on_error = raise_on_error
+ self.register_class("@import", ImportDefinition)
def register_directive(
self, prefix: str, parserfunc: ParserFuncT, single_line: bool
@@ -222,34 +236,3 @@ class Parser:
except Exception as ex:
logger.error("In line {}, cannot add '{}' {}".format(lineno, line, ex))
raise ex
-
-
-@dataclass(frozen=True)
-class DefaultsDefinition:
- """Definition for the @default directive"""
-
- content: Tuple[Tuple[str, str], ...]
-
- @classmethod
- def from_lines(cls, lines, non_int_type=float) -> DefaultsDefinition:
- source_iterator = SourceIterator(lines)
- next(source_iterator)
- out = []
- for lineno, part in source_iterator:
- k, v = part.split("=")
- out.append((k.strip(), v.strip()))
-
- return DefaultsDefinition(tuple(out))
-
-
-@dataclass(frozen=True)
-class ImportDefinition:
- """Definition for the @import directive"""
-
- path: str
-
- @classmethod
- def from_string(
- cls, definition: str, non_int_type: type = float
- ) -> ImportDefinition:
- return ImportDefinition(definition[7:].strip())
diff --git a/pint/registry.py b/pint/registry.py
index d60475e..e722417 100644
--- a/pint/registry.py
+++ b/pint/registry.py
@@ -42,6 +42,7 @@ import locale
import re
from collections import ChainMap, defaultdict
from contextlib import contextmanager
+from dataclasses import dataclass
from decimal import Decimal
from fractions import Fraction
from numbers import Number
@@ -64,7 +65,7 @@ from typing import (
Union,
)
-from . import parser, registry_helpers, systems
+from . import registry_helpers, systems
from ._typing import F, QuantityOrUnitLike
from .compat import HAS_BABEL, babel_parse, tokenizer
from .context import Context, ContextChain, ContextDefinition
@@ -82,7 +83,7 @@ from .errors import (
RedefinitionError,
UndefinedUnitError,
)
-from .parser import DefaultsDefinition, Parser
+from .parser import Parser
from .pint_eval import build_eval_tree
from .systems import Group, GroupDefinition, System, SystemDefinition
from .util import (
@@ -118,6 +119,24 @@ T = TypeVar("T")
_BLOCK_RE = re.compile(r"[ (]")
+@dataclass(frozen=True)
+class DefaultsDefinition:
+ """Definition for the @default directive"""
+
+ content: Tuple[Tuple[str, str], ...]
+
+ @classmethod
+ def from_lines(cls, lines, non_int_type=float) -> DefaultsDefinition:
+ source_iterator = SourceIterator(lines)
+ next(source_iterator)
+ out = []
+ for lineno, part in source_iterator:
+ k, v = part.split("=")
+ out.append((k.strip(), v.strip()))
+
+ return DefaultsDefinition(tuple(out))
+
+
@functools.lru_cache()
def pattern_to_regex(pattern):
if hasattr(pattern, "finditer"):
@@ -307,9 +326,6 @@ class BaseRegistry(metaclass=RegistryMeta):
self._initialized = True
def _register_directives(self) -> None:
- self._register_directive(
- "@import", self._loader_import, parser.ImportDefinition
- )
self._register_directive("@alias", self._load_alias, AliasDefinition)
self._register_directive("@defaults", self._load_defaults, DefaultsDefinition)
@@ -323,10 +339,6 @@ class BaseRegistry(metaclass=RegistryMeta):
"""Loader for an @alias directive"""
self._define_alias(alias_definition)
- def _loader_import(self, source_iterator: SourceIterator) -> None:
- """ """
- # TODO who should handled this?
-
def __deepcopy__(self, memo) -> "BaseRegistry":
new = object.__new__(type(self))
new.__dict__ = copy.deepcopy(self.__dict__, memo)
@@ -571,7 +583,12 @@ class BaseRegistry(metaclass=RegistryMeta):
and therefore should be loaded from the package. (Default value = False)
"""
- loaders = {}
+ loaders = {
+ AliasDefinition: self._define,
+ UnitDefinition: self._define,
+ DimensionDefinition: self._define,
+ PrefixDefinition: self._define,
+ }
p = Parser(self.non_int_type)
for prefix, (loaderfunc, definition_class) in self._directives.items():
loaders[definition_class] = loaderfunc
@@ -581,17 +598,11 @@ class BaseRegistry(metaclass=RegistryMeta):
for definition_file in parsed_files[::-1]:
for lineno, definition in definition_file.parsed_lines:
loaderfunc = loaders.get(definition.__class__, None)
- if loaderfunc is not None:
+ if loaderfunc:
+ # this will skip definitions for which
+ # there is no loader
+ # (for example the import directive)
loaderfunc(definition)
- else:
- try:
- self._define(definition)
- except Exception as ex:
- logger.error(
- "In line {}, cannot add '{}' {}".format(
- lineno, definition, ex
- )
- )
def _build_cache(self) -> None:
"""Build a cache of dimensionality and base units."""