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.
Hello, world
Section titled “Hello, world”Python runs a file top to bottom. For now, Amethyst programs start at a main method.
print("Hello, world!")def main: Void puts "Hello, world!"endAbout end
Section titled “About 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.
def classify(score: int) -> str: if score >= 50: return "pass" else: return "fail"def classify(score: Int): String if score >= 50 "pass" else "fail" endendNo 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.
Type hints that mean it
Section titled “Type hints that mean it”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 |
None becomes nil
Section titled “None becomes nil”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.
user = find_user(user_id) # User | Noneif user is not None: print(user.name)user = find_user(user_id) # User?if user puts user.name # narrowed to Userend&. 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.
Truthiness
Section titled “Truthiness”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.
if items: print("has items")if items.count > 0 puts "has items"endClasses
Section titled “Classes”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.
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)class User property name: String getter age: Int
def initialize(name: String, age: Int) @name = name @age = age end
def greet: String "Hi, #{@name}" endend
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.
Keyword arguments
Section titled “Keyword arguments”A parameter marked with a double colon is a keyword parameter, and must be passed by
name, like a Python parameter after *.
def create(*, name: str, role: str = "user") -> User: ...
create(name="Ada", role="admin")def create(name:: String, role:: String = "user"): Userend
create(name: "Ada", role: "admin")Comprehensions become blocks
Section titled “Comprehensions become blocks”There are no comprehensions. Collections have methods that take a block, and you chain them.
names = [u.name for u in users if u.active]total = sum(item.price for item in cart)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.
Exceptions
Section titled “Exceptions”try/except/finally becomes begin/rescue/ensure, and raise is still
raise. Exceptions are .NET exceptions, whose names end in Exception rather than
Error.
try: parse(path)except FileNotFoundError as e: log(str(e))finally: cleanup()begin parse(path)rescue FileNotFoundException => e log e.messageensure cleanupendThere’s no with statement. Instead, objects that need cleaning up are Disposable,
and use does what with does:
with open("data.csv") as f: print(f.read())StreamReader.new("data.csv").use do |reader| puts reader.read_to_endendNearly 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.
async def fetch(url: str) -> str: response = await client.get(url) return await response.text()async def fetch(url: String): String response = await http.get(url) await response.read_bodyendAmethyst 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.
Decorators aren’t attributes
Section titled “Decorators aren’t attributes”@[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.
Everything else
Section titled “Everything else”| 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 |