Understanding Python's variable scoping rules is crucial for writing clean and efficient code. Variable scope refers to the context in which a variable is defined and can be accessed. Python has four main scopes: local, enclosing, global, and built-in. If a variable is defined inside a function, it is considered local to that function. If it is declared outside any function, it is global. Enclosing scope refers to variables in nested functions. Built-in scope holds variables that Python defines by default.
Here's an example to illustrate Python's variable scoping:
def outer_function():
x = "outer x"
def inner_function():
nonlocal x
x = "inner x"
print(x)
inner_function()
print(x)
outer_function()
In this example, the variable x
starts in the outer function's scope. The inner function modifies x
using the nonlocal
keyword, reflecting the change when it is printed from the outer function.
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?