Python Functions
Pick Python in the language menu of the Functions tab to write your server rules in Python. NetStack compiles your code on the server and runs it in the same sandbox as JavaScript, with the same limits and the same all-or-nothing behaviour.
Anatomy
Define a function called run. It receives ctx and args, and whatever it returns is sent back to the caller.
def run(ctx, args):
return {"ok": True}
argsis a dict with whatever your game passed tocall(). Read it withargs["itemId"]orargs.get("itemId", default).- Return anything that converts to JSON: dicts, lists, tuples, strings, numbers,
True/FalseandNone. - Helper functions, constants and
lambdaare fine in the same file. Type hints are accepted and not checked. - You can
import math,random,json,timeandstring. Other modules are not available.
import math
MAX_HP = 100
def heal_amount(level: int) -> int:
return math.floor(10 + level * 1.5)
def run(ctx, args):
hp = ctx.player.get("hp", MAX_HP)
hp = min(MAX_HP, hp + heal_amount(ctx.player.get("level", 1)))
ctx.player.set("hp", hp)
return {"hp": hp}
The API in Python
| Python | What it does |
|---|---|
ctx.player.id |
ID of the calling player. |
ctx.player.get(key, default=None) |
Read a Player Property. Returns default when it is missing. |
ctx.player.set(key, value) |
Write a Player Property. |
ctx.player.delete(key) |
Remove a Player Property. |
ctx.player.has(key), ctx.player.keys() |
Check for a property, list property names. |
ctx.players |
List of everyone in the room. Each has id, get, set, delete, has and keys. |
ctx.room.get / set / delete / has / keys |
Room Properties. |
ctx.room.broadcast(event, data) |
Send an event to every player in the room. |
ctx.room.state(player_id), ctx.room.state_at(player_id, time) |
A player's realtime state, now or at a recent server time. |
ctx.global.get / set / delete / has / keys |
Global Properties shared by every room. |
ctx.now |
Server time in milliseconds when the call started. |
print(...), ctx.log(...) |
Write a line that shows up in test runs. |
raise NetStackError(code, message) |
Reject the call. fail(code, message) does the same. |
global is a Python keyword, but ctx.global works as an attribute name in NetStack Functions, so you can write it as shown.
get() returns a copy. Change the copy, then set() it back:
def run(ctx, args):
inventory = ctx.player.get("inventory", [])
if args["itemId"] not in inventory:
raise NetStackError("ITEM_NOT_OWNED", "You do not own that item.")
inventory.remove(args["itemId"])
ctx.player.set("inventory", inventory)
ctx.room.broadcast("itemUsed", {"playerId": ctx.player.id, "itemId": args["itemId"]})
return {"remaining": len(inventory)}
Rejecting a call
Raise NetStackError(code, message). The caller receives the code and message, and none of the changes made so far are kept. You can catch ordinary exceptions with try/except as usual. An uncaught exception such as KeyError is reported as FUNCTION_ERROR with the exception and line number, which you can see in the Test run panel.
def run(ctx, args):
amount = args.get("amount")
if not isinstance(amount, int) or not 1 <= amount <= 100:
raise NetStackError("BAD_AMOUNT", "Amount must be between 1 and 100.")
gold = ctx.player.get("gold", 0) + amount
ctx.player.set("gold", gold)
return {"gold": gold}
Working with other players
def run(ctx, args):
target = next((p for p in ctx.players if p.id == args["toPlayerId"]), None)
if target is None:
raise NetStackError("PLAYER_NOT_IN_ROOM", "That player is not here.")
target.set("gold", target.get("gold", 0) + 5)
return {"ok": True, "scores": {p.id: p.get("score", 0) for p in ctx.players}}
What is supported
- Functions with default values and
*args, calls with keyword arguments (add(b=1, a=2)),lambda, closures,globalandnonlocal. if/elif/else,forandwhile(withelse),break,continue,try/except/else/finally,raise,assert,del, the walrus operator.- Lists, dicts, sets and tuples with their common methods, unpacking (
a, *rest = items), slicing, and list, dict and set comprehensions and generator expressions. - Strings with their common methods, f-strings with format specs (
f"{ratio:.2f}"),str.format()and%formatting. - Builtins such as
len,range,enumerate,zip,sorted,min,max,sum,any,all,map,filter,round,isinstanceandnext.
Classes, decorators, with, yield generators, **kwargs and keyword-only parameters are not supported. You get a clear error with a line number if you use one. Use dicts and functions instead of classes.
Generator expressions such as sum(x for x in items) work, but they are evaluated straight away rather than lazily. That only matters for very large or endless sequences, which the CPU limit would stop anyway.
Numbers
int and float behave as in Python for everyday game maths (7 // 2, -7 // 2, round(2.5), 2 ** 10), but all numbers are 64-bit floating point on the server, like JSON. Integers are exact up to 2^53; very large integers lose precision instead of growing without limit. Properties are stored as JSON, so 2.0 comes back as 2.
Limits
The same as every Function: 150 ms of CPU and 32 MB of memory per call, no network, filesystem or timers, and up to 20,000 characters of source. See Limits and plans.