Skip to content

First Program

Write a program

Create a file hello.p4:

def greet(name: str) -> str:
return "Hello, " + name + "!"
def main() -> None:
print(greet("world"))

Compile and run

Terminal window
./py4 hello.p4
./hello
# Hello, world!

py4 compiles to a native binary by default. No separate gcc invocation is needed.

To specify a custom output path:

Terminal window
./py4 -o build/hello hello.p4
./build/hello

To inspect the generated C source:

Terminal window
./py4 --emit-c hello.p4
# produces hello.c

A more complete example

Note that self in methods is always explicitly typed with the class name:

enum Direction:
NORTH
SOUTH
EAST
WEST
class Point:
x: int
y: int
def move(self: Point, d: Direction) -> Point:
if d == Direction.NORTH:
return Point(self.x, self.y + 1)
elif d == Direction.SOUTH:
return Point(self.x, self.y - 1)
elif d == Direction.EAST:
return Point(self.x + 1, self.y)
return Point(self.x - 1, self.y)
def main() -> None:
p = Point(0, 0)
p = p.move(Direction.NORTH)
p = p.move(Direction.EAST)
print(p.x) # 1
print(p.y) # 1

What gets generated

py4 emits a single .c file containing:

  • Struct definitions for your classes and tuple shapes
  • Enum definitions
  • One specialized list/dict runtime per container type you use
  • Static C functions for each py4 function and method
  • A main() entry point

This C file is then compiled with GCC (or Clang via --backend clang) to produce the final binary.