Welcome to VarScope’s documentation#
A simple Python library for creating local scopes.
This module consists of a single function
scope()
that creates Scope
context manager, to be used
with Python’s with
statement:
# Scope A
with scope():
# Scope B (includes A)
# Scope A
Scroll below for usage examples.
- class Scope(*names: str) None [source]#
Context manager for encapsulating variables in a scope.
See
scope()
for a detailed description.References#
https://pydev.blogspot.com/2014/02/changing-locals-of-frame-frameflocals.html
- keep(*names: str) None [source]#
Tells the context manager to keep specific variable names after the scope was exited.
Examples#
>>> from varscope import scope >>> with scope() as s: ... a = 1 ... b = 2 ... s.keep("a") ... >>> a 1 >>> b Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'b' is not defined
- scope(*names: str) varscope.Scope [source]#
Returns a context manager to encapsulate all the variables, making them inaccessible afterward.
Variables that are created in a given scope will not be accessible outside of this scope.
Optionally, you can specify variable names from outside the scope that must be moved inside. Upon exiting the scope, they will be deleted.
- Parameters:
names (
str
) – Variable names to be moved inside the scope, as they were defined there.- Return type:
Examples#
>>> from varscope import scope >>> a = 1 >>> with scope(): ... b = 2 ... >>> a 1 >>> b Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'b' is not defined
Variables that are redefined will get their original value back, as of when the scope was entered.
>>> from varscope import scope >>> a = 1 >>> with scope(): ... a = 2 ... print(a) 2 >>> a 1
Mutating an object will still keep its effects outside the scope.
>>> from varscope import scope >>> d = {} >>> with scope(): ... d["a"] = 1 ... >>> d {'a': 1}
You can also specify variables (by name) that must be moved inside the scope, and deleted afterward.
>>> from varscope import scope >>> a = 1 >>> with scope("a"): ... print(a) ... 1 >>> a Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'a' is not defined