Probably the best way to simulate block scopes in Python

Overview

Probably the best way to simulate block scopes in Python.

This is a package, as it says on the tin, to emulate block scoping in Python, the lack of which being a clever design choice yet sometimes a trouble.

In addition to readability and code organization (where your mileage may vary), block scoping in particular helps to have variables garbage collected as soon as possible, which is useful for situations where variables may refer to expensive resources (e.g. GPU arrays).

This package is designed to be as easy to use as possible, with the least mental burden on the user, whilst the implementation being necessarily confusing and cryptic due to the tricks used.

Usage

Other than installing from PyPI the usual way, you can also directly download scoping.py to where your main script is to use the package.

To start a scoped block (where the variables created in the block is to be deleted after the block) use

with scoping():
    #scoped code here........

Within a block, you can selectively let a variable leak through to the outer scope (as in the traditional behavior in Python) by passing the name (as a string) to

scoping.keep()

If you are only after using the library, just consider scoping and scoping.keep as some kind of quasi-keywords rather than real classes/objects.

See

from scoping import scoping
a = 2
with scoping():
    assert(2 == a)
    a = 3
    b = 4
    scoping.keep('b')
    assert(3 == a)
assert(2 == a)
assert(4 == b)

In the rare case that you would like to reserve the word "scoping" for other uses, the class can be renamed arbitrarily using the following trick:

import scoping
class VeryScoped(scoping.scoping): pass
del scoping

Then the names "VeryScoped" and "VeryScoped.keep" can be used instead, whereas the name "scoping" can be put to other uses at will.

Blocks can be nested, as well as used in functions (unlike prior art), at the price of relying on some CPython specific feature.

Motivation/Prior Art

See https://github.com/bskinn/tempvars with a similar idea but not the intended use for general programming, as well as a more mentally demanding interface (IMHO).

Compatibility

Tested with python 3.6/7/8/9 under Linux

You might also like...
Block when attacker want to bypass the limit of request

Block when attacker want to bypass the limit of request

Programming in Bioinformatics, Block 3

Programming in Bioinformatics - Block 3 I. Setting up Environment and Running the Code Create the environment using the pibi_block3.yml file with the

A collection of UIKit components that can be used as a Wagtail StreamField block.
A collection of UIKit components that can be used as a Wagtail StreamField block.

Wagtail UIKit Blocks A collection of UIKit components that can be used as a Wagtail StreamField block. Available UIKit components Container Grid Headi

"Cambio de monedas" Change-making problem with Python, dynamic programming best solutions,

Change-making-problem / Cambio de monedas Entendiendo el problema Dada una cantidad de dinero y una lista de denominaciones de monedas, encontrar el n

World's best free and open source ERP.
World's best free and open source ERP.

World's best free and open source ERP.

A tool to allow New World players to calculate the best place to put their Attribute Points for their build and level
A tool to allow New World players to calculate the best place to put their Attribute Points for their build and level

New World Damage Simulator A tool designed to take a characters base stats including armor and weapons, level, and base damage of their items (slash d

Digdata presented 'BrandX' as a clothing brand that wants to know the best places to set up a 'pop up' store.

Digdata presented 'BrandX' as a clothing brand that wants to know the best places to set up a 'pop up' store. I used the dataset given to write a program that ranks these places.

Saturne best tools pour baiser tout le système de discord
Saturne best tools pour baiser tout le système de discord

Installation | Important | Discord 🌟 Comme Saturne est gratuit, les dons sont vraiment appréciables et maintiennent le développement! Caractéristique

A flexible free and unlimited python tool to translate between different languages in a simple way using multiple translators.
A flexible free and unlimited python tool to translate between different languages in a simple way using multiple translators.

deep-translator Translation for humans A flexible FREE and UNLIMITED tool to translate between different languages in a simple way using multiple tran

Owner
null
A redesign of our previous Python World Cup, aiming to simulate the 2022 World Cup all the way from the qualifiers

A redesign of our previous Python World Cup, aiming to simulate the 2022 World Cup all the way from the qualifiers. This new version is designed to be more compact and more efficient and will reflect the improvements in our programming ability.

Sam Counsell 1 Jan 7, 2022
Implementation of the Angular Spectrum method in Python to simulate Diffraction Patterns

Diffraction Simulations - Angular Spectrum Method Implementation of the Angular Spectrum method in Python to simulate Diffraction Patterns with arbitr

Rafael de la Fuente 276 Dec 30, 2022
A Python library to simulate a Zoom H6 recorder remote control

H6 A Python library to emulate a Zoom H6 recorder remote control Introduction This library allows you to control your Zoom H6 recorder from your compu

Matias Godoy 68 Nov 2, 2022
This is a Python program I wrote to simulate the solar system with 79 lines of code.

Solar System With Python This is a Python program I wrote to simulate the solar system with 79 lines of code. Required modules tkinter, math, time Why

Mehmet Aydoğmuş 1 Oct 26, 2021
Hook and simulate global keyboard events on Windows and Linux.

keyboard Take full control of your keyboard with this small Python library. Hook global events, register hotkeys, simulate key presses and much more.

BoppreH 3.2k Jan 1, 2023
Manipulation OpenAI Gym environments to simulate robots at the STARS lab

liegroups Python implementation of SO2, SE2, SO3, and SE3 matrix Lie groups using numpy or PyTorch. [Documentation] Installation To install, cd into t

STARS Laboratory 259 Dec 11, 2022
MeerKAT radio telescope simulation package. Built to simulate multibeam antenna data.

MeerKATgen MeerKAT radio telescope simulation package. Designed with performance in mind and utilizes Just in time compile (JIT) and XLA backed vectro

Peter Ma 6 Jan 23, 2022
This is a library for simulate probability theory problems specialy conditional probability

This is a library for simulate probability theory problems specialy conditional probability. It is also useful to create custom single or joint distribution with specific PMF or PDF to get probability table and genearte data based on probability function.

Mohamadreza Kariminejad 6 Mar 30, 2022
Block fingerprinting for the beacon chain, for client identification & client diversity metrics

blockprint This is a repository for discussion and development of tools for Ethereum block fingerprinting. The primary aim is to measure beacon chain

Sigma Prime 49 Dec 8, 2022
Block the annoying Token Grabbers on your discord

General We have seen that in the last time many discord servers are infected by fake discord nitro links we want to put an end to this and have develo

BadTiger Network 2 Jul 16, 2022