reading-notes

Game of Greed Reading Part 2

it happens when you declare variables inside functions and when you try to access them outside this function, you have an error that these variables are not defined, this thing has to do with scope, so what is scope ?

the scope of a name defines the area of a program in which you can unambiguously access that name, such as variables, functions, objects, and so on.

mainly, there are two general scopes:

scopes

in the picture above indicates the scope (or namespace, almost) process in python and the allowed access to them, clearly, the built-in methods and variable are accessable anywhere in everyone’s code .

for more understanding, here is this code:

scopes

Scope VS namespace:

Using the LEGB Rule for Python Scope

The letters in LEGB stand for Local, Enclosing, Global, and Built-in:

scopes in python

Modifying the Behavior of a Python Scope

Python provides two keywords that allow you to modify the content of global and nonlocal names. These two keywords are:

counter = 0 # A global name def update_counter(): global counter # Declare counter as global

counter = counter + 1  # Successfully update the counter

update_counter() counter output: 1

def func():

var = 100  # A nonlocal variable

def nested():
     nonlocal var  # Declare var as nonlocal
     var += 100
nested()
 print(var)

func()

output: 200

Bringing Names to Scope With import

the following code shows for an example of what happens when you import some standard modules and names:

>>> dir()

['__annotations__', '__builtins__',..., '__spec__']

>>> import sys

>>> dir()

['__annotations__', '__builtins__',..., '__spec__', 'sys']

>>> import os

>>> dir()

['__annotations__', '__builtins__',..., '__spec__', 'os', 'sys']

>>> from functools import partial

>>> dir()

['__annotations__', '__builtins__',..., '__spec__', 'os', 'partial', 'sys']

Discovering Unusual Python Scopes