The algorithm: each of the 9 digits is multiplied by a weight from 9 down to 1, the products are summed, and the result must be divisible by 11 — with one special case handled below.
def valida_nif(numero: str) -> bool: pass
Workflow
We will build this function incrementally, adding one testing technique at a time:
Doctests inside the docstring
Logging for debugging
Unit tests (unittest)
pytest as the runner
Coverage report
Property-based tests (Hypothesis)
Benchmark
Version 1 — the first (buggy) implementation
def valida_nif(numero): """Valida o NIF. versão 1""" soma = 0 posicao = 9 for digito in numero: soma += int(digito) * posicao posicao -= 1 return soma % 11 == 0print(valida_nif('999999990')) # oito '9' e um zero: Trueprint(valida_nif('999999999')) # nove '9': False# print(valida_nif('9999O9999')) # um 'O' (letra O) no meio: BUG!
Output:
True
False
Crash instead of False
Uncommenting the last line raises ValueError: invalid literal for int() with base 10: 'O'. The function crashes on non-numeric input instead of returning False. A validator must never raise on bad input — that is the contract we will test.
Version 2 — guarding against invalid input
def valida_nif(numero): """Valida o NIF. versão 2""" if not numero.isdigit(): return False soma = 0 posicao = 9 for digito in numero: soma += int(digito) * posicao posicao -= 1 return soma % 11 == 0print(valida_nif('999999990')) # Trueprint(valida_nif('999999999')) # Falseprint(valida_nif('9999O9999')) # False — input guard works
Output:
True
False
False
str.isdigit()
.isdigit() is a cheap pre-condition check. It is not perfect — it accepts exotic Unicode digits — but it is enough here, and Hypothesis will probe the edge cases later.
Validation with doctest
Version 3 — executable documentation
Tests live inside the docstring and run with doctest.testmod(). Any output mismatch fails the test.
# v3import doctestdef valida_nif(numero): """Valida o NIF. versão 3 >>> valida_nif('999999990') True >>> valida_nif('999999999') False >>> valida_nif('9999O9999') False """ if not numero.isdigit(): return False soma = 0 posicao = 9 for digito in numero: soma += int(digito) * posicao posicao -= 1 return soma % 11 == 0if __name__ == '__main__': doctest.testmod(verbose=False)
Takeaway
With no output, the doctests passed. Run with verbose=True to see every example listed. Doctests are excellent for documenting expected behaviour, but they are not a substitute for a full test suite.
Version 4 — debugging with logging
The first version misses a real-world case: NIFs whose weighted sum is ≡ 1 (mod 11) and end in '0'. We add that special case — and use logging to follow the computation.
# v4import doctestimport logginglogging.basicConfig(level=logging.DEBUG)def valida_nif(numero): """Valida o NIF. versão 4 >>> valida_nif('999999990') True >>> valida_nif('999999999') False >>> valida_nif('9999O9999') False >>> valida_nif('592889050') True """ if not numero.isdigit(): return False soma = 0 posicao = 9 for digito in numero: logging.debug('soma: %s | posicao: %s', soma, posicao) soma += int(digito) * posicao posicao -= 1 resto = soma % 11 if resto != 0 and numero[-1] == '0': resto = (soma + 10) % 11 logging.debug('resto: %s', resto) return resto == 0if __name__ == '__main__': doctest.testmod()
For 592889050 the sum is 265, so 265 % 11 == 1. Under the official rule, a remainder of 1 means the check digit is '0' — the (soma + 10) % 11 adjustment captures exactly that. Check 265 % 11 == 0 → False, but (265 + 10) % 11 == 0 → True.
Logging in production
logging.basicConfig(level=logging.DEBUG) at module import time is fine for a lab script, but keep the level configurable in real projects — never hard-code DEBUG.
Version 5 — the final implementation
Type hints, a comprehension for the weighted sum, a length guard and clean logging. This is the version we will test exhaustively.
# v5 (final)import doctestimport loggingdef valida_nif(numero: str) -> bool: """Valida o NIF. versão 5 (final) >>> valida_nif('999999990') True >>> valida_nif('999999999') False >>> valida_nif('9999O9999') False >>> valida_nif('592889050') True >>> valida_nif('123456789') False >>> valida_nif('') False """ if not numero.isdigit() or len(numero) != 9: return False soma = sum(int(digito) * peso for digito, peso in zip(numero, range(9, 0, -1))) resto = soma % 11 if resto != 0 and numero[-1] == '0': resto = (soma + 10) % 11 logging.debug('resto: %s', resto) return resto == 0if __name__ == '__main__': logging.basicConfig(level=logging.INFO) # DEBUG logs stay hidden doctest.testmod()
What changed in v5
zip(numero, range(9, 0, -1)) replaces the manual posicao counter — the original off-by-one source.
len(numero) != 9 rejects strings that are not exactly 9 digits (e.g. '123').
Type hints (numero: str -> bool) document the contract.
logging.basicConfig moved out of the function — configuration belongs at the entry point, not in library code.
Unit tests with unittest
Real NIFs come from the public list of valid numbers; the negative database covers digit-level mutations of those.
import loggingimport unittestclass TestValidaNIF(unittest.TestCase): def test_positive(self): db = ['292849680', '245832343', '121588955', '592889050', '522523129', '620365498', '636695468', '998113360', '999999990'] for nif in db: with self.subTest(nif=nif): self.assertTrue(valida_nif(nif)) def test_negative(self): db = ['292849681', '245382343', '12158895', '59288905000', '999999999', '123', '639566468'] for nif in db: with self.subTest(nif=nif): self.assertFalse(valida_nif(nif)) def test_dummy(self): db = ['', 'abc', '\r\n', '999999abc', '9999O9999', '999999990abc', 'a12345678', 'username!', '@999999990', ' 999999990', '999999990 ', '1234567890'] for nif in db: with self.subTest(nif=nif): self.assertFalse(valida_nif(nif))if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) unittest.main(argv=['first-arg-is-ignored'], exit=False)
Output:
...
----------------------------------------------------------------------
Ran 3 tests in 0.005s
OK
Why subTest?
Without subTest, the first failure aborts the loop and hides the rest. With subTest, unittest reports every failing NIF in one run — invaluable when the db lists grow.
Convention matters
Test files must be discoverable: name them test_*.py and keep tests out of the same module as the production code for anything beyond a lab exercise.
Running tests with pytest
pytest runs the very same unittest classes without modification, plus any test_ functions, and its assertion introspection shows the actual vs. expected values.
@pytest.mark.parametrize gives every case its own test in the report, with a readable id. This is the pytest equivalent of self.subTest — prefer it when starting from pytest.
Measuring coverage
Coverage answers the question: which lines did my tests never execute?
---------- coverage: platform linux, python 3.12 ----------
Name Stmts Miss Cover Missing
---------------------------------------
nif.py 8 0 100%
---------------------------------------
TOTAL 8 0 100%
100% is a checkpoint, not a finish line
Coverage shows executed lines, not tested logic. That is exactly why the next section exists: property-based testing explores combinations no hand-written test would try.
Property-based testing with Hypothesis
Hypothesis generates hundreds of inputs per test and tries to falsify the property you claim.
The check digit helper
To generate valid NIFs, we factor out the check digit computation:
import doctestdef check_digit(string_num: str) -> str: """Calcula o dígito de controlo de um NIF (8 primeiros dígitos). >>> check_digit('99999999') '0' >>> check_digit('74089837') '9' >>> check_digit('28702400') '8' """ if not string_num.isdigit(): raise ValueError('requires 8 digits') soma = sum(int(digito) * peso for digito, peso in zip(string_num, range(9, 1, -1))) resto = soma % 11 if resto < 2: return '0' return str(11 - resto)if __name__ == '__main__': doctest.testmod()
..
----------------------------------------------------------------------
Ran 2 tests in 0.169s
OK
A property that exposes a bug
Wait — test_random_text_is_never_valid passes only because every arbitrary string happens to be invalid. This is a good teaching trap: it looks like a vacuous test, but Hypothesis would shrink any counterexample to a minimal failing input. If the validator ever becomes too permissive (e.g. someone “fixes” isdigit to isnumeric), Hypothesis finds the exotic Unicode digit that breaks it.
The value of Hypothesis
The first property tests rejection over the whole space of strings; the second tests acceptance over all 90 million numeric NIFs. Together they bound the function’s behaviour far better than any fixed database — and on failure, Hypothesis prints the minimal counterexample plus the seed to reproduce it.
Benchmark: how fast is the validator?
A validator may run millions of times in a data pipeline — performance is a legitimate test dimension. timeit with a perf-style harness:
test_nif_bench.py::test_valida_nif_benchmark
Name (time in ns) Min Mean StdDev
test_valida_nif_benchmark 301.0120 329.5541 18.4127
Reading the benchmark
The mean (~330 ns) matters less than StdDev: a stable validator shows low variance. If a refactor doubles the mean or the spread, that shows up immediately — before production.
Exercise: profile the validator with pyinstrument
timeit and pytest-benchmark answer how fast? — they do not answer where does the time go? For that we need a statistical profiler: pyinstrument samples the call stack at regular intervals and aggregates the results, at a fraction of the overhead of cProfile.
Install
python -m pip install pyinstrument
Step 1 — build a workload
Profiling a single 330 ns call tells us nothing; the function must run long enough to be sampled. Simulate a data-pipeline load by validating a batch of NIFs:
# profile_nif.pyfrom pyinstrument import Profilerfrom nif import valida_nifbatch = ['292849680', '245832343', '592889050', '999999990', '999999999', '9999O9999', '123', '']profiler = Profiler()with profiler: for _ in range(100_000): for nif in batch: valida_nif(nif)profiler.print()
On this version the profile is dominated by two things: the isdigit() guard and the generator expression for the weighted sum. That is a healthy profile — the cost lives in the function’s own logic, not in hidden imports, logging calls or accidental I/O. The point of the exercise is to verify exactly that.
Step 3 — what to investigate
Logging tax: change logging.basicConfig(level=logging.INFO) in nif.py to logging.DEBUG and re-profile. Compare the samples attributed to logging. Why is the extra cost small here (lazy % formatting, filtered records) but potentially large in loops that format eagerly (f-strings in log calls)?
Compare versions: import both the v1 loop implementation and the v5 zip-comprehension version, profile each, and decide whether the refactor changed the hotspot.
Profiler overhead: run the same workload under cProfile and compare wall time against pyinstrument. Note how the statistical approach stays out of the way, while the deterministic approach slows the run but gives exact call counts.
Step 4 — deliverable
Add a test_nif_profile.py that fails if the batch regresses: benchmark it with pytest-benchmark as before, but now use the pyinstrument profile to justify the refactor decision — “the cost is in the weighted sum, so a table-driven translate/str.maketrans or a precomputed digit table is the right next step” (or refute it, if the profile says otherwise).
Profile before you optimize
A profiler changes the answer to which line is slow? only when the workload is representative. Use a realistic batch (mixed valid/invalid inputs, as here) — profiling only '999999990' would hide the isdigit() branch entirely.