Navigating the scope in Python can be tricky, whether it’s understanding variable accessibility within classes, instances, or even the broader context of where your Python interpreter or kernel is operating. It’s essential to grasp these scopes to avoid potential pitfalls when handling variables.
LEGB rules: local enclosing, global and Built-in
A simple but effective example:

global x can cause issues hence be very careful using it.
Corey’s other course on class variable, where an init variable is easy, but can also define class variable like pay raise_amount:

we can emp_1.raise_amoutn=1.05 to just change emp_1 instance’s variable.
Closure also worth learning: closure unlike a plain function, allows the function to access those captured variables through the closure’s reference to them, even when the function is invoked outside their scope. reference Corey Schafer’s link for concrete example.

A relevant example on my own codes when set up a temp_path, where to place it? global or local? I need to set temp_path, then write to excel with this parameter, then run os.remove(temp_path). The problem is the middle step is executed by from pa_coverage import *, where the global variable temp_path is not taken in, hence it’s need to be “repetitive” within and out of the pa_coverage script.
Another point to note is Python’s import caching mechanism. To get around this, you can use importlib.reload, encapsulate the behavior you want in functions, or conditionally execute script code within the module. These methods will give you the control to execute the module’s code as needed.