Skip to content

Fix UnboundLocalError from length variable defined in a sibling block - #210

Open
Sanjays2402 wants to merge 1 commit into
horejsek:masterfrom
Sanjays2402:fix/length-variable-scope-157
Open

Fix UnboundLocalError from length variable defined in a sibling block#210
Sanjays2402 wants to merge 1 commit into
horejsek:masterfrom
Sanjays2402:fix/length-variable-scope-157

Conversation

@Sanjays2402

Copy link
Copy Markdown

Closes #157

create_variable_with_length and friends deduplicate by variable name only, but the assignment is emitted inside whatever conditional block is open. minLength defines data_len under if isinstance(data, str):, so a schema that also sets minItems made the minItems block reuse data_len under if data_is_list:, where it was never assigned — fastjsonschema.validate({"minItems": 1, "minLength": 1}, ["str"]) raised UnboundLocalError.

Each generated variable now records the block scope it was defined in and is only reused from an enclosing block, so a sibling block emits its own assignment. Blocks merged by the indent optimizer share a scope since they share generated code. Added regression tests for the min and max pairs; both fail with the reported UnboundLocalError without the fix.

The create_variable_* helpers deduplicate generated assignments by name
alone, but the assignment is often emitted inside a conditional block.
minLength defines data_len under `if isinstance(data, str):`, so a
schema combining minLength with minItems made the minItems block reuse
data_len under `if data_is_list:`, where it was never assigned:

    fastjsonschema.validate({"minItems": 1, "minLength": 1}, ["str"])
    UnboundLocalError: local variable 'data_len' referenced before assignment

Track the block scope each generated variable was defined in and only
reuse it from an enclosing block, so a sibling block emits its own
assignment. Blocks merged by the indent optimizer share a scope, as they
share generated code.

Closes horejsek#157
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Getting UnboundLocalError

1 participant