Summary
extract_text_before() and extract_text_after() (in unstructured/cleaners/extract.py) raise an UnboundLocalError instead of a clear error when the given pattern does not occur in the text at all. The helper they call, _get_indexed_match(), tries to build a "not found" message using a loop variable that was never assigned because the loop body never ran.
Reproduction
from unstructured.cleaners.extract import extract_text_before
# "xyz" does not appear in the text, so there are zero matches
extract_text_before("hello world", "xyz")
Actual
UnboundLocalError: cannot access local variable 'i' where it is not associated with a value
Expected
Either the intended ValueError ("Result with index 0 was not found.") or a graceful no-match result. The confusing UnboundLocalError should not surface.
Root cause
In _get_indexed_match:
for i, result in enumerate(re.finditer(pattern, text)):
if i == index:
regex_match = result
if regex_match is None:
raise ValueError(f"Result with index {index} was not found. The largest index was {i}.")
When re.finditer(pattern, text) yields no matches, the for loop never executes, so i is never bound. The regex_match is None branch is then taken and the f-string references {i}, which raises UnboundLocalError before the intended ValueError can be raised. This is the normal "pattern absent" path, so any caller of extract_text_before / extract_text_after with a pattern that is not present hits it.
Suggested fix
Initialize the counter before the loop so the message is well-defined on zero matches, e.g.:
i = -1
for i, result in enumerate(re.finditer(pattern, text)):
...
if regex_match is None:
raise ValueError(
f"Result with index {index} was not found."
+ (f" The largest index was {i}." if i >= 0 else " No matches were found.")
)
Happy to send a small PR with a regression test if that helps.
Summary
extract_text_before()andextract_text_after()(inunstructured/cleaners/extract.py) raise anUnboundLocalErrorinstead of a clear error when the given pattern does not occur in the text at all. The helper they call,_get_indexed_match(), tries to build a "not found" message using a loop variable that was never assigned because the loop body never ran.Reproduction
Actual
Expected
Either the intended
ValueError("Result with index 0 was not found.") or a graceful no-match result. The confusingUnboundLocalErrorshould not surface.Root cause
In
_get_indexed_match:When
re.finditer(pattern, text)yields no matches, theforloop never executes, soiis never bound. Theregex_match is Nonebranch is then taken and the f-string references{i}, which raisesUnboundLocalErrorbefore the intendedValueErrorcan be raised. This is the normal "pattern absent" path, so any caller ofextract_text_before/extract_text_afterwith a pattern that is not present hits it.Suggested fix
Initialize the counter before the loop so the message is well-defined on zero matches, e.g.:
Happy to send a small PR with a regression test if that helps.