Skip to content

Amethyst for Python developers

You’ll find a surprising amount of home here: def, snake_case names, async def, and generics in square brackets. Those brackets are borrowed from Python’s type hints (and Ruby’s RBS), so list[int] becomes Array[Int] and your eyes won’t need to adjust.

Then there’s end. We owe you an apology for end.

The other big difference is that Amethyst compiles to .NET IL before it runs, and the compiler checks every type on the way. In Python, a type hint is a suggestion. In Amethyst, it’s the law.

Python runs a file top to bottom. For now, Amethyst programs start at a main method.

Python
print("Hello, world!")
Amethyst
def main: Void
puts "Hello, world!"
end

Blocks finish with end, not with a change in indentation. Your indentation is now decorative. Keep it tidy anyway; we can’t enforce it, but your colleagues can.

Python
def classify(score: int) -> str:
if score >= 50:
return "pass"
else:
return "fail"
Amethyst
def classify(score: Int): String
if score >= 50
"pass"
else
"fail"
end
end

No colons at the end of lines, either. if is an expression, and the last expression in a method is its return value, so return is optional.

Annotations use the same name: Type shape you already write, and the return type goes after a colon instead of ->. The difference is that the compiler checks them, so passing a str where an int belongs is a build error, not a surprise at runtime.

Local variables are inferred, and you can leave out a parameter’s type entirely: the compiler works out what the argument must provide from how the method uses it, then checks every caller. That’s duck typing, checked before the duck takes off. See Structural Typing.

A public method without a return type returns nil, whatever its last expression is. If you want a value back, write the type.

Python Amethyst
int, float, bool, str Int, Float, Bool, String
list[int] Array[Int] (a .NET List<int>)
dict[str, int] Hash[String, Int]
tuple[str, int] Tuple[String, Int]
-> None Leave out the return type, or write Void

Types can’t be nil unless you say so. String? is Amethyst’s Optional[str], or str | None. Unlike Python’s hints, the compiler won’t let you call a method on it until you’ve checked.

Python
user = find_user(user_id) # User | None
if user is not None:
print(user.name)
Amethyst
user = find_user(user_id) # User?
if user
puts user.name # narrowed to User
end

&. calls a method only if the value isn’t nil, so user&.address&.city replaces a chain of is not None checks.

T? is the only union there is. For “an int or a str”, use a protocol, a common base class or a complex enum.

This is the one that will catch you. In Amethyst, only nil and false are falsy. 0, "" and an empty array are all truthy. To make sure that never surprises anyone, if only accepts a Bool or a nullable value, and anything else doesn’t compile.

Python
if items:
print("has items")
Amethyst
if items.count > 0
puts "has items"
end

There’s no self parameter. Instance variables start with @, __init__ is initialize, and you create objects with .new. property and getter replace @property and its setter.

Python
class User:
def __init__(self, name: str, age: int):
self.name = name
self._age = age
@property
def age(self) -> int:
return self._age
def greet(self) -> str:
return f"Hi, {self.name}"
user = User("Ada", 36)
Amethyst
class User
property name: String
getter age: Int
def initialize(name: String, age: Int)
@name = name
@age = age
end
def greet: String
"Hi, #{@name}"
end
end
user = User.new("Ada", 36)

f-strings become "#{...}" interpolation, which works in any double-quoted string. Methods with no parameters don’t need parentheses, at the definition or the call.

A parameter marked with a double colon is a keyword parameter, and must be passed by name, like a Python parameter after *.

Python
def create(*, name: str, role: str = "user") -> User:
...
create(name="Ada", role="admin")
Amethyst
def create(name:: String, role:: String = "user"): User
end
create(name: "Ada", role: "admin")

There are no comprehensions. Collections have methods that take a block, and you chain them.

Python
names = [u.name for u in users if u.active]
total = sum(item.price for item in cart)
Amethyst
names = users.select(&:active?).map(&:name)
total = cart.reduce(0) { |sum, item| sum + item.price }
Python Amethyst
[f(x) for x in xs] xs.map { |x| f(x) }
[x for x in xs if p(x)] xs.select { |x| p(x) }
any(...) / all(...) any? / all?
sorted(xs, key=...) sort_by
len(xs) xs.count
lambda x: x * 2 ->(x: Int) { x * 2 }

map and select live in Enumerable[T], along with the rest.

try/except/finally becomes begin/rescue/ensure, and raise is still raise. Exceptions are .NET exceptions, whose names end in Exception rather than Error.

Python
try:
parse(path)
except FileNotFoundError as e:
log(str(e))
finally:
cleanup()
Amethyst
begin
parse(path)
rescue FileNotFoundException => e
log e.message
ensure
cleanup
end

There’s no with statement. Instead, objects that need cleaning up are Disposable, and use does what with does:

Python
with open("data.csv") as f:
print(f.read())
Amethyst
StreamReader.new("data.csv").use do |reader|
puts reader.read_to_end
end

Nearly identical. Write async def and await, and give the return type as the value you’ll eventually get. The compiler wraps it in a .NET Task.

Python
async def fetch(url: str) -> str:
response = await client.get(url)
return await response.text()
Amethyst
async def fetch(url: String): String
response = await http.get(url)
await response.read_body
end

Amethyst has no GIL, because it isn’t interpreted. Its own model for threads and parallelism hasn’t been designed yet, so for now, async is what there is.

@[Serializable] looks like a decorator, but it isn’t one. An attribute is metadata, compiled into the assembly for something else to read. It doesn’t wrap or change the method. Something closer to decorators, attribute macros, is planned for later.

Python Amethyst
snake_case names snake_case names. Finally, a language that agrees with you. C# callers see PascalCase
import json use System::Text::Json
pip install requests am add <package>, from NuGet
requirements.txt, pyproject.toml project.am
MAX_RETRIES = 3 (by convention) MAX_RETRIES = 3, and the compiler holds you to it
x if cond else y cond ? x : y
and / or / not && / || / !. and, or and not exist, but bind loosely and are meant for flow control
for item in items: for item in items, or items.each { |item| … }
# comment # comment. Something had to stay the same
Interpreted Compiled to .NET IL