Leap is an experimental package written to enable the utilization of C-like goto statements in Python functions

Overview

Leap

Leap is an experimental package written to enable the utilization of C-like goto statements in Python functions. It currently supports only Python 3.6 and 3.7.

Examples

Labels are added using a label keyword, and gotos are added using a goto keyword. Here is a simple function that prints the contents of a list, using the goto keyword.

from leap.goto import goto

@goto
def print_list(lst):
    i = 0
    label .start
    item = lst[i]
    print(item)
    if i == len(lst) - 1:
        goto .end
    else:
        i += 1
        goto .start
    label .end

# test
print_list(range(5))

# this outputs
0
1
2
3
4

We can also utilize the goto decorator, if we need to pass arguments, to perform checks.

Below is a simple function that builds a list given a start value an end value, and an optional step value. Here, formal arguments max_gotos and max_labels are sentries that ensures the maximum number of goto and label statements in build_list() does not exceed the actual parameter values. If it does, an exception is raised accordingly.

debug (False by default, only explicitly declared for example sake) is also set to False to disable internal-processing outputs.

from leap.goto import goto

@goto(debug=False, max_gotos=3, max_labels=3)
def build_list(begin_val, end_val, step=1):
    lst = []
    val = begin_val
    label .begin
    if val >= end_val:
        goto .end
    lst.append(val)
    val += step
    goto .begin
    label .end
    return lst

print(build_list(1, 10))  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

Below is a simple function err() that will fail at decoration time.

from leap.goto import goto

@goto(max_labels=2)
def err():
    label .start1
    label .start2
    label .start3


# Traceback (most recent call last):
# ...
# LabelLimitError: Too many labels in function. Max allowed: 2

The exception was triggered because max_labels was exceeded. The same applies to goto statements (in this case we have a GotoLimitError).

Duplicate labels are also not allowed (this can lead to some form of ambiguity).

from leap.goto import goto

@goto(max_labels=3)
def err2():
    label .start
    label .start


# Traceback (most recent call last):
# ...
# DuplicateLabelError: Duplicate labels found: `start`

Labels that are not declared in a function cannot be referenced in a goto statement.

Below is a simple example that will fail.

from leap.goto import goto

@goto(max_labels=2)
def err3():
    x = 0
    goto .end
    label .start


# Traceback (most recent call last):
# ...
# LabelNotFoundError: Label `end` was not found.

Functions err(), err2(), and err3() will fail even before any of them are called.

Why?

Why not? I mean, it's a perfect excuse to test bytecode editing/rewriting possibilities in Python.

Tests

See the tests folder for tests and other examples. To run the tests, simply cd to the Leap directory, and do: python -m tests.test -v

Limitations

Only functions/methods are supported (may be easily inferable from the decorator syntax). Nested functions/methods are not supported, that is, labels cannot be declared in external or enclosing functions and referenced in another function be it inner or enclosing.

Installation

Clone this repo, and do:

cd leap
python setup.py install

Bugs/Features

Please file an issue.

License

MIT

You might also like...
A library that modifies python source code to conform to pep8.

Pep8ify: Clean your code with ease Pep8ify is a library that modifies python source code to conform to pep8. Installation This library currently works

Code generation and code search for Python and Javascript.
Code generation and code search for Python and Javascript.

Codeon Code generation and code search for Python and Javascript. Similar to GitHub Copilot with one major difference: Code search is leveraged to mak

AST based refactoring tool for Python.

breakfast AST based refactoring tool. (Very early days, not usable yet.) Why 'breakfast'? I don't know about the most important, but it's a good meal.

Refactoring Python Applications for Simplicity

Python Refactoring Refactoring Python Applications for Simplicity. You can open and read project files or use this summary 👇 Concatenate String my_st

[CVPR2021] Look before you leap: learning landmark features for one-stage visual grounding.
[CVPR2021] Look before you leap: learning landmark features for one-stage visual grounding.

LBYL-Net This repo implements paper Look Before You Leap: Learning Landmark Features For One-Stage Visual Grounding CVPR 2021. Getting Started Prerequ

Write a program that works out whether if a given year is a leap year
Write a program that works out whether if a given year is a leap year

Leap Year 💪 This is a Difficult Challenge 💪 Instructions Write a program that works out whether if a given year is a leap year. A normal year has 36

A tool that helps keeping track of your AWS quota utilization
A tool that helps keeping track of your AWS quota utilization

aws-quota-checker A tool that helps keeping track of your AWS quota utilization. It'll determine the limits of your AWS account and compare them to th

A crowdsourced dataset of dialogues grounded in social contexts involving utilization of commonsense.

A crowdsourced dataset of dialogues grounded in social contexts involving utilization of commonsense.

RockNext is an Open Source extending ERPNext built on top of Frappe bringing enterprise ready utilization.
RockNext is an Open Source extending ERPNext built on top of Frappe bringing enterprise ready utilization.

RockNext is an Open Source extending ERPNext built on top of Frappe bringing enterprise ready utilization.

Decorators for maximizing memory utilization with PyTorch & CUDA

torch-max-mem This package provides decorators for memory utilization maximization with PyTorch and CUDA by starting with a maximum parameter size and

A Sklearn-like Framework for Hyperparameter Tuning and AutoML in Deep Learning projects. Finally have the right abstractions and design patterns to properly do AutoML. Let your pipeline steps have hyperparameter spaces. Enable checkpoints to cut duplicate calculations. Go from research to production environment easily.
A hack for writing switch statements with type annotations in Python.

py_annotation_switch A hack for writing switch statements in type annotations for Python. Why should I use this? You most definitely should not use th

An easy python calculator for those who want's to know how if statements, loops, and imports works give it a try!

A usefull calculator for any student or anyone who want's to know how to build a simple 2 mode python based calculator.

fixup: Automatically add and remove python import statements

fixup: Automatically add and remove python import statements The goal is that running fixup my_file.py will automatically add or remove import stateme

The pyrelational package offers a flexible workflow to enable active learning with as little change to the models and datasets as possible
The pyrelational package offers a flexible workflow to enable active learning with as little change to the models and datasets as possible

pyrelational is a python active learning library developed by Relation Therapeutics for rapidly implementing active learning pipelines from data management, model development (and Bayesian approximation), to creating novel active learning strategies.

flake8 plugin which forbids match statements (PEP 634)

flake8-match flake8 plugin which forbids match statements (PEP 634)

flake8 plugin to catch useless `assert` statements

flake8-useless-assert flake8 plugin to catch useless assert statements Download or install on the PyPI page Violations Code Description Example ULA001

💰 Import your ING Germany bank statements via FinTS into YNAB.
💰 Import your ING Germany bank statements via FinTS into YNAB.

Import your ING Germany bank statements via FinTS into YNAB. Setup Before setting this up, please register your FinTS product – it's free and takes on

A pyparsing-based library for parsing SOQL statements

CONTRIBUTORS WANTED!! Installation pip install python-soql-parser or, with poetry poetry add python-soql-parser Usage from python_soql_parser import p

Owner
Creating.
null
A simple Python bytecode framework in pure Python

A simple Python bytecode framework in pure Python

null 3 Jan 23, 2022
Awesome autocompletion, static analysis and refactoring library for python

Jedi - an awesome autocompletion, static analysis and refactoring library for Python Jedi is a static analysis tool for Python that is typically used

Dave Halter 5.3k Dec 29, 2022
a python refactoring library

rope, a python refactoring library ... Overview Rope is a python refactoring library. Notes Nick Smith <[email protected]> takes over maintaining rope

null 1.5k Dec 30, 2022
Find dead Python code

Vulture - Find dead code Vulture finds unused code in Python programs. This is useful for cleaning up and finding errors in large code bases. If you r

Jendrik Seipp 2.4k Dec 27, 2022
Safe code refactoring for modern Python.

Safe code refactoring for modern Python projects. Overview Bowler is a refactoring tool for manipulating Python at the syntax tree level. It enables s

Facebook Incubator 1.4k Jan 4, 2023
A system for Python that generates static type annotations by collecting runtime types

MonkeyType MonkeyType collects runtime types of function arguments and return values, and can automatically generate stub files or even add draft type

Instagram 4.1k Dec 28, 2022
Programmatically edit text files with Python. Useful for source to source transformations.

massedit formerly known as Python Mass Editor Implements a python mass editor to process text files using Python code. The modification(s) is (are) sh

null 106 Dec 17, 2022
Tool for translation type comments to type annotations in Python

com2ann Tool for translation of type comments to type annotations in Python. The tool requires Python 3.8 to run. But the supported target code versio

Ivan Levkivskyi 123 Nov 12, 2022
Bottom-up approach to refactoring in python

Introduction RedBaron is a python library and tool powerful enough to be used into IPython solely that intent to make the process of writing code that

Python Code Quality Authority 653 Dec 30, 2022
Removes commented-out code from Python files

eradicate eradicate removes commented-out code from Python files. Introduction With modern revision control available, there is no reason to save comm

Steven Myint 146 Dec 13, 2022