|
10 | 10 |
|
11 | 11 | """
|
12 | 12 |
|
| 13 | +from __future__ import annotations |
| 14 | + |
13 | 15 | import itertools
|
14 | 16 | import random
|
15 | 17 | import re
|
@@ -50,7 +52,7 @@ class Rut:
|
50 | 52 |
|
51 | 53 | """
|
52 | 54 |
|
53 |
| - def __init__(self, value: str, validate_dv: bool = False) -> None: |
| 55 | + def __init__(self, value: str | Rut, validate_dv: bool = False) -> None: |
54 | 56 | """
|
55 | 57 | Constructor.
|
56 | 58 |
|
@@ -79,8 +81,7 @@ def __init__(self, value: str, validate_dv: bool = False) -> None:
|
79 | 81 | self._dv = match_groups['dv']
|
80 | 82 |
|
81 | 83 | if validate_dv:
|
82 |
| - if Rut.calc_dv(self._digits) != self._dv: |
83 |
| - raise ValueError("RUT's \"digito verificador\" is incorrect.", value) |
| 84 | + self.validate_dv(raise_exception=True) |
84 | 85 |
|
85 | 86 | ############################################################################
|
86 | 87 | # properties
|
@@ -137,6 +138,22 @@ def __hash__(self) -> int:
|
137 | 138 | # Objects are hashable so they can be used in hashable collections.
|
138 | 139 | return hash(self.canonical)
|
139 | 140 |
|
| 141 | + ############################################################################ |
| 142 | + # custom methods |
| 143 | + ############################################################################ |
| 144 | + |
| 145 | + def validate_dv(self, raise_exception: bool = False) -> bool: |
| 146 | + """ |
| 147 | + Whether the "digito verificador" of the RUT is correct. |
| 148 | +
|
| 149 | + :param raise_exception: Whether to raise an exception if validation fails. |
| 150 | + :raises ValueError: |
| 151 | + """ |
| 152 | + is_valid = self.calc_dv(self._digits) == self._dv |
| 153 | + if not is_valid and raise_exception: |
| 154 | + raise ValueError("RUT's \"digito verificador\" is incorrect.", self.canonical) |
| 155 | + return is_valid |
| 156 | + |
140 | 157 | ############################################################################
|
141 | 158 | # class methods
|
142 | 159 | ############################################################################
|
|
0 commit comments