Skip to content

Repository files navigation

ideas

Ideas: making it easier to extend Python’s syntax.

ideas logo

Documentation

Everything you need can be found here. However, some of the documentation might be slightly out of date.

Installation

python -m pip install ideas

Depending on your OS, you might need to write python3 or py instead of python in the above.

Dependencies

  • token-utils
  • Python 3.8+ (Subject to change; it might work with older versions)

Usage

ideas -a my_cool_new_syntax my_program[.py]

Admitedly this is a bit terse ... Let's go into a bit more details.

Usage in more details

As a specific example of a new syntax, suppose that you want to use function as a keyword in Python, to mean the same thing as lambda, enabling you to write

# my_program.py

square = function x: x**2
print(f"{square(4)} is the square of 4.")

if __name__ == "__main__":
    print("This is run as the main module.")

You can do this using an import hook.

The simplest (but flawed) way to create such an import hook with ideas would be as follows:

from ideas import import_hook

def transform(source, **kwargs):
    return source.replace("function", "lambda")

import_hook.create_hook(transform_source=transform, name=__main__)

Then, you'd need to use it. Since there is already an example import hook that does this, we'll use it instead. All you have to do is instruct Python to add the import hook, and it will be used from that point on. There are two ways to do so.

The first method would be to create a second file which adds the required import hook and then imports your program.

# Let's call this 'loader.py'

from ideas.examples import function_keyword
function_keyword.add_hook()

import my_program

You could then run this second file the normal way.

python loader.py

So, my_program.py, and any other module that could be loaded by it would recognize that function is a valid alternative to lambda. However, using this method, loader would be the __main__ script, and the code block defined by if __name__ == "__main__": in my_program would be ignored.

The second way is to skip the creation of a loader, and run my_program directly using ideas:

ideas -a function_keyword my_program

This method will ensure that my_program is the __main__ module. In this example, ideas is an entry point for the project equivalent to writing py -m ideas.

Many more examples can be found in the documentation, including a better way to create such an import hook and information about a console (REPL) that supports code transformations.

Tools

This project uses black for formatting, pytest for running tests, and flake8 for linting with custom settings compatible with black.

License

MIT

About

Easy creation of custom import hooks to experiment on alternatives to Python's syntax; see https://aroberge.github.io/ideas/docs/html/

Topics

Resources

Contributing

Stars

90 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages