AmpliPy - Accelerated Python
AmpliPy is a Python preprocessor written in Python that aims to make Python code faster to write and easier to read. It introduces lots of helpful new blocks, statements and syntax.
How do I use it?
Write your .apy
file, then run the amplipy
command with your input file.
amplipy program.apy
This outputs a file with the same name into the same directory, but with the .py
extension.
What syntax does it introduce?
Pattern matching
Many languages have a match
or switch
construct, which is like an extended chain of elif
statements. In some languages, there is a "wildcard" syntax too, allowing some parts of the input to be ignored.
This kind of block is now available in AmpliPy, and often looks much prettier than a chain of elif
s - just like Python code should. Turn this:
if result[0] == 0:
print("First result is 0")
elif result[1] == 0:
print("Second result is 0")
else:
print("Neither result is 0")
Into this:
match result:
case (0, ...):
print("First result is 0")
case (..., 0):
print("Second result is 0")
case ...:
print("Neither result is 0")
These match
and case
statements are incredibly powerful and work with a wide range of different data types. Check out the wiki!
Shorthand lambdas
The lambda syntax for Python is quite long compared to other languages and looks ugly:
lambda x: x + 1
As an alternative, AmpliPy introduces the shorthand lambda syntax. This is composed by a single-item set containing a bitwise OR; after all, AmpliPy uses valid Python 3 syntax:
{x | x + 1} # Produces `lambda x: x + 1`
{_ | foo()} # Produces `lambda: foo()`
{(x, y, z) | x + y + z} # Produces `lambda x, y, z: x + y + z`
Multi-assigning
Let's say you want to make 3 empty lists, a
, b
and c
. How many times have you fallen into this notorious trap?
>>> a = b = c = []
>>> a.append("Foo")
>>> b
['Foo']
When you change one, it changes all the others too! That's because they're all referencing the same object, as a is b is c
.
But no more! With AmpliPy, you can avoid headaches and use a simple syntax to do exactly what you wanted to:
a, b, c = [], ...
Simple ranges
Haskell has a very pretty way of writing ranges:
Prelude> [2, 4..10]
[2,4,6,8,10]
Prelude> [1..10]
[1,2,3,4,5,6,7,8,9,10]
What if you could do that in Python? With AmpliPy, you can!
[2, 4, ..., 10] # Produces `range(2, 11, 2)`
[1, ..., 10] # Produces `range(1, 11)` (WIP)
The range calculation happens at runtime, so it even works with variables.
[a, b, ..., c] #Produces `range(a, c + (b - a), b - a)`