Zebra for Python programmers
Python's shape, with the checks moved to compile time.
If you write Python, most of Zebra will read as familiar: indentation instead
of braces, def, for x in xs, strings that interpolate. What changes
is that types are declared, the program is compiled before it runs, and the compiler refuses
a class of mistakes Python finds only when the line executes.
Each pair below is checked by a script: the Python program is run with Python 3, the Zebra program with the latest Zebra release, and both must print the output shown under them.
The same program, twice
Functions, defaults and interpolation
Parameters carry types. A default comes after the type, and a call names
an argument with a colon. Every string interpolates with ${...}; there is no
f prefix. 0..n counts from 0 up to, not including, n, like
range(n).
def greet(name, times=1):
for i in range(times):
print(f"hello, {name} #{i}")
greet("ada")
greet("alan", times=2)def greet(name: str, times: int = 1)
for i in 0..times
print("hello, ${name} #${i}")
def main()
greet("ada")
greet("alan", times: 2)hello, ada #0 hello, alan #0 hello, alan #1
Classes
Fields are declared with their types. The constructor is
cue init, and there is no self parameter: inside a method a field
is just its name.
class Counter:
def __init__(self, start=0):
self.count = start
def bump(self):
self.count += 1
return self.count
c = Counter(10)
c.bump()
print(c.bump())
print(Counter().bump())class Counter
var count: int
cue init(start: int = 0)
count = start
def bump(): int
count += 1
return count
def main()
var c = Counter(10)
c.bump()
print(c.bump())
print(Counter().bump())12 1
Dictionaries and None
A dict literal builds a HashMap. Its get
returns an optional, int?, which the compiler will not let you use as an
int until you have handled nil: here with orelse, or by comparing
with nil.
ages = {"ada": 36, "alan": 41}
print(ages.get("ada", 0))
print(ages.get("grace", 0))
age = ages.get("grace")
if age is None:
print("grace: unknown")def main()
var ages = {"ada": 36, "alan": 41}
print(ages.get("ada") orelse 0)
print(ages.get("grace") orelse 0)
var age = ages.get("grace")
if age == nil
print("grace: unknown")36 0 grace: unknown
Comprehensions
There are no comprehensions; lists have filter and
map, and a lambda is def(x) = expr. Annotating the results with
their type keeps this program compiling on 0.9.0, which does not infer them.
nums = [1, 2, 3, 4, 5, 6]
squares = [n * n for n in nums if n % 2 == 0]
print(squares)
print(len(squares))def main()
var nums = [1, 2, 3, 4, 5, 6]
var evens: List(int) = nums.filter(def(n) = n % 2 == 0)
var squares: List(int) = evens.map(def(n) = n * n)
print(squares)
print(squares.len)[4, 16, 36] 3
Conditions
elif is else if, block headers have no
colon, len(w) is w.len, and the conditional expression is the call
form if(c, a, b).
for w in ["a", "bb", "ccc"]:
if len(w) == 1:
size = "short"
elif len(w) == 2:
size = "medium"
else:
size = "long"
print(f"{w} {size} {'even' if len(w) % 2 == 0 else 'odd'}")def main()
for w in ["a", "bb", "ccc"]
var size = "long"
if w.len == 1
size = "short"
else if w.len == 2
size = "medium"
print("${w} ${size} ${if(w.len % 2 == 0, "even", "odd")}")a short odd bb medium even ccc long odd
Exceptions
A function that can fail says throws in its signature.
At the call, ? passes the error on and catch replaces it with a
value; catch |e| names it. Leaving both off is a compile error, so a call that
can fail is visible where it is made.
def parse_age(s):
if not s.lstrip("-").isdigit():
raise ValueError(f"not a number: {s}")
n = int(s)
if n < 0:
raise ValueError(f"negative: {n}")
return n
print(parse_age("42"))
try:
a = parse_age("-3")
except ValueError:
a = -1
print(a)
try:
msg = parse_age("x")
except ValueError as e:
msg = len(str(e))
print(msg)def parseAge(s: str): int throws
var n = s.tryInt()
if n == nil
raise "not a number: ${s}"
if n < 0
raise "negative: ${n}"
return n
def main()
print(parseAge("42")?)
var a = parseAge("-3") catch -1
print(a)
var msg = parseAge("x") catch |e| e.message.len
print(msg)42 -1 15
Same code, different answer
These are the ones to know: the two programs look alike, both compile without a warning, and they print different things.
print(-7 // 2)
print(-7 % 2)
print(7 // 2)
print(7 / 2)
print("zebra"[0])
-4 1 3 3.5 z
def main()
print(-7 / 2)
print(-7 % 2)
print(7 / 2)
print(7 / 2.0)
print("zebra"[0])
-3 -1 3 3.5 122
- Division truncates toward zero, as in C, Go and Java; Python's
//rounds toward negative infinity./on two integers is integer division; make one side a float for a fractional result. - The remainder takes the sign of the left operand, so that
(a / b) * b + a % b == aholds with Zebra's division. - Indexing a string gives a byte, not a one-character string: 122 is
z. Use.chars()to walk characters; on text that is not ASCII, a byte is part of a character.
Habits the compiler catches
Where a Python spelling does not carry over, the error says what to write instead.
def double(n: int) -> int
return n * 2
def main()
print(double(4))
py_rettype.zbr:1:20: error: the return type is written with a colon, `def f(x: int): int`, not `->` (QUICKSTART §1.5)
def main()
var n = 3
if n > 2:
print("big")
py_colon.zbr:3:13: error: a block header ends at the end of the line with no colon -- indent the body on the next line; `header: stmt` is the one-line form (QUICKSTART §1.5)
def main()
var name = "ada"
print(f"hi {name}")
py_fstr.zbr:3:11: error: no `f"..."` prefix: every Zebra string interpolates -- write "n=${x}" (QUICKSTART §1.5)
Spellings that change
| Python | Zebra |
|---|---|
None, True, False | nil, true, false |
len(xs) | xs.len |
range(3) | 0..3 |
elif | else if |
a if c else b | if(c, a, b) |
lambda x: x * 2 | def(x) = x * 2 |
f"n={x}" | "n=${x}" |
s[1:3], s[::-1] | s[1..3], s.reverse() |
def f() -> int: | def f(): int |
class Dog(Animal): | no inheritance: class Dog adds Barking for shared code, class Dog implements Animal for an interface |
The full list, with the error each Python spelling produces, is section 1.5 of the language reference.
What Python does not have
The reasons to switch are the checks: contracts on functions and classes, nil tracked in the type, unions whose every case must be handled, errors visible at the call, and tests in the same file as the code. The tour shows each of them compiling, or refusing to.