From 0a6dffa3911a7f5ebeb8b021a30874e6e1436371 Mon Sep 17 00:00:00 2001 From: William Song <30965609+Freakwill@users.noreply.github.com> Date: Tue, 5 Dec 2023 14:33:49 +0800 Subject: [PATCH] meta --- pyrimidine/errors.py | 20 +++++++++++++++----- pyrimidine/meta.py | 11 ++++++++++- tests/test_meta.py | 3 +-- 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/pyrimidine/errors.py b/pyrimidine/errors.py index ad916d2..c20791f 100755 --- a/pyrimidine/errors.py +++ b/pyrimidine/errors.py @@ -5,16 +5,26 @@ class UnknownSizeError(Exception): def __init__(self, cls): self.cls = cls - + def __str__(self): - return f'The size of `{self.cls}` is unkown, the object could not be generated.' + return f'The size of class `{self.cls.__name__}` is unkown, the object could not be generated.' class UnavalibleAttributeError(AttributeError): - + def __init__(self, cls, attr_name): self.cls = cls self.attr_name = attr_name - + + def __str__(self): + return f'Did not define attribute `{self.attr_name}` for the class `{self.cls.__name__}`.' + + +class RegesterError(AttributeError): + + def __init__(self, cls, attr_name): + self.cls = cls + self.attr_name = attr_name + def __str__(self): - return f'Did not define attribute `{self.attr_name}` for `{self.cls}`.' \ No newline at end of file + return AttributeError(f'`{attr_name}` is an attribute of the class `{self.cls.__name__}`, and would not be redefined.') diff --git a/pyrimidine/meta.py b/pyrimidine/meta.py index bb2fd05..20a6c4c 100755 --- a/pyrimidine/meta.py +++ b/pyrimidine/meta.py @@ -257,13 +257,22 @@ def _regester_map(self, name, key=None, force=True): def m(obj, *args, **kwargs): return obj.map(key, obj.__elements, *args, **kwargs) if not force and hasattr(self, name): - raise AttributeError(f'`{name}` is an attribute of {self.__class__.__name__}, and would not be regestered.') + raise RegesterError(self.__class__, name) setattr(self, name, MethodType(m, self)) attrs.update({ 'regester_map': _regester_map }) + def _regester(self, name, key, force=True): + if not force and hasattr(self, name): + raise RegesterError(self.__class__, name) + setattr(self, name, MethodType(key, self)) + + attrs.update({ + 'regester': _regester + }) + return super().__new__(cls, name, bases, attrs) def __call__(self, *args, **kwargs): diff --git a/tests/test_meta.py b/tests/test_meta.py index 9cb5298..45d00ff 100644 --- a/tests/test_meta.py +++ b/tests/test_meta.py @@ -20,7 +20,7 @@ def after_setter(self): C = self.mc c = C([UserString('I'), UserString('love'), UserString('you')], lasting='for ever') - C.set_methods(n_elems=lambda c: 1) + C.set(n_elems=lambda c: 1) self.C = C self.c = c @@ -41,7 +41,6 @@ def n_vowels(s): c.regester_map('length', n_vowels) assert list(c.length()) == [1, 2, 2] - def test_subclass(self): C = self.C class D(C):