Hasty Briefsbeta

Bilingual

Shadowing in Python gave me an UnboundLocalError

a year ago
  • #Scoping
  • #Python
  • #UnboundLocalError
  • Shadowing a variable in Python can lead to an UnboundLocalError due to Python's scoping rules.
  • Variables are defined for their entire scope in Python, meaning if a variable is defined anywhere in a function, it is considered local to the entire function.
  • The example provided shows how renaming a loop variable to shadow an outer function's parameter caused an UnboundLocalError.
  • Python's scoping rules differ from languages like Rust, where shadowing is idiomatic and does not cause similar issues.
  • Understanding Python's scoping rules is crucial to avoid common pitfalls like the UnboundLocalError.