Papiha Joharapurkar

LEGB scoping rules

  • Came across this video while trying to understand the terminology behind something I had known intuitively about the scope of variables in Python
  • LEGB stands for Local, Enclosing, Global, Built-In rules
  • local - variables defined within a function
  • if updating variables within function, updates will remain in the context of function unless variables being updated are defined as global
  • enclosing - in local scope of enclosing function (function levels up)
  • can use nonlocal statement i.e. to affect outer function variable updates
  • global - declared at top of module (global keywords not necessary)
  • if updating global variable inside function, need to explicitly state global keyword to make the outer global variable update
  • built-in - names preassigned in Python i.e. min/max
  • can actually be overwritten with custom functions, so need to be careful to not do that! (I did not know this actually)
  • the order is important, it tells you order in which the rules are applied

All daily logs