Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Upgrading from 0.10 to 0.11

Pyfun 0.11 brings the language’s spelling in line with Python wherever the two say the same thing. Booleans are True and False, the string type is str, every library name is snake_case, and a multi-line if opens its branches with :. Your 0.10 programs need some renaming.

You don’t have to find the changes yourself. Every old spelling is an error that names the new one, and the compiler reports all of them, in every module of a project, with the file and line of each. This page lists every change so you know what to expect, and it’s a reference for the errors you’ll see along the way.

The upgrade, step by step

  1. Install 0.11.

    pip install --upgrade pyfun-lang
    

    Update the editor extension too, so the language server and the command line agree.

  2. Fix the syntax errors. Run pyfun check on your program, or on the file you run if it’s a project. The first run reports the syntax changes: true and false, a multi-line if written with then, and a value named in. All of them arrive in that one run.

  3. Fix the name errors. Run pyfun check again. Once the program parses, the checker reports every renamed library member, every string in a type, and the other changes below, again all in one run. Each error says what to write:

    error: `sortBy` is not a member of `List` (did you mean `List.sort_by`?)
     --> main.pyfun:4:50
      |
    4 |   users |> List.filter (fun u -> u.age >= 18) |> List.sortBy (fun u -> u.name)
      |                                                  ^^^^^^^^^^^
    
  4. Format and test. pyfun fmt is new in 0.11. It settles spacing and indentation and keeps your line breaks and comments, so it’s safe to run over code you’ve just edited. Then run your program or your tests as usual.

  5. Check what reads your output. If Python code imports your compiled modules, or a tool reads the compiler’s messages, read the last two sections of this page.

Syntax

Booleans are True and False

Write them as Python does.

let ready = true          # 0.10
let ready = True

The old spelling is answered with “Pyfun spells this True, as Python does”.

A multi-line if opens with :

When a branch sits on its own indented lines, write if cond:, elif cond: and else:, as in Python. In 0.10 the same branch followed then or a bare else.

let grade n =             # 0.10
  if n >= 90 then
    "A"
  elif n >= 80 then
    "B"
  else
    "C"
let grade n =
  if n >= 90:
    "A"
  elif n >= 80:
    "B"
  else:
    "C"

A branch on the same line keeps then, exactly as before:

let abs x = if x < 0 then -x else x

You choose the opener branch by branch, so one chain can mix the two. The rule is the same inside parentheses and inside a builder’s braces (async { }, result { }), where 0.10 kept then even for a branch on its own lines:

let check x =
  result {
    let! y =
      if x == 0:
        Error "zero"
      else:
        Ok x
    return y
  }

Each old spelling is an error that names the new one: “a branch on its own indented lines opens with :, as in Python: write if cond:, not then”.

in is a keyword

in and not in are now Python’s membership operators (2 in xs, "ell" in "hello"), so in can no longer name a value. Rename any binding or parameter called in.

Types

The string type is str

Write str wherever a type is written: in a record or constructor, in an extern signature, and in an opaque type.

type User = { name: string, age: int }     # 0.10
opaque type UserId = string
type User = { name: str, age: int }
opaque type UserId = str

The JSON decoder for strings follows: Decode.string is Decode.str. The String module keeps its name.

Library names

Every standard library name is snake_case, and lookups that return an Option no longer carry a try prefix, because the type already says so. These are all the names that changed.

The rename covers the standard library only. Your own functions and values keep whatever names you gave them, and a camelCase name of yours still compiles.

List

0.100.11
List.chunkBySizeList.chunk_by_size
List.countByList.count_by
List.distinctByList.distinct_by
List.dropWhileList.drop_while
List.findIndexList.find_index
List.groupByList.group_by
List.insertAtList.insert_at
List.isEmptyList.is_empty
List.maxByList.max_by
List.minByList.min_by
List.removeAtList.remove_at
List.sortByList.sort_by
List.sortByDescendingList.sort_by_descending
List.sortDescendingList.sort_descending
List.splitAtList.split_at
List.sumByList.sum_by
List.takeWhileList.take_while
List.updateAtList.update_at

Seq

0.100.11
Seq.distinctBySeq.distinct_by
Seq.dropWhileSeq.drop_while
Seq.initInfiniteSeq.init_infinite
Seq.isEmptySeq.is_empty
Seq.ofListSeq.of_list
Seq.sumBySeq.sum_by
Seq.takeWhileSeq.take_while
Seq.toListSeq.to_list

Set and Map

0.100.11
Set.isEmptySet.is_empty
Set.isSubsetSet.is_subset
Set.isSupersetSet.is_superset
Set.ofListSet.of_list
Set.toListSet.to_list
Map.findOrMap.find_or
Map.isEmptyMap.is_empty
Map.ofListMap.of_list
Map.toListMap.to_list
Map.tryFindMap.find

Option and Result

0.100.11
Option.isNoneOption.is_none
Option.isSomeOption.is_some
Option.orElseOption.or_else
Option.toListOption.to_list
Option.toResultOption.to_result
Option.withDefaultOption.with_default
Result.isErrorResult.is_error
Result.isOkResult.is_ok
Result.mapErrorResult.map_error
Result.orElseResult.or_else
Result.toListResult.to_list
Result.toOptionResult.to_option
Result.withDefaultResult.with_default

String and Format

trimStart and trimEnd take Python’s names for the same operation.

0.100.11
String.endsWithString.ends_with
String.fromFloatString.from_float
String.fromIntString.from_int
String.isEmptyString.is_empty
String.ofListString.of_list
String.splitLinesString.split_lines
String.startsWithString.starts_with
String.toFloatString.to_float
String.toIntString.to_int
String.toListString.to_list
String.trimEndString.rstrip
String.trimStartString.lstrip
String.tryIndexOfString.index_of
Format.padLeftFormat.pad_left
Format.padRightFormat.pad_right

Decode and Async

0.100.11
Decode.andThenDecode.and_then
Decode.decodeStringDecode.decode_string
Decode.oneOfDecode.one_of
Decode.stringDecode.str
Async.toThreadAsync.to_thread

The fields of Exception

The error that try hands you has snake_case fields too.

0.100.11
e.errorKinde.error_kind
e.errorMessagee.error_message

Your own computation expression builders

If you wrote a builder module, rename two of its functions. A builder’s return! calls return_from, and its yield! calls yield_from.

0.100.11
let returnFrom m = …let return_from m = …
let yieldFrom m = …let yield_from m = …

The error points at the builder expression and names the member it looked for: “return_from is not a member of Maybe”.

Projects

A multi-word module is a snake_case file

import TrainTimes reads train_times.pyfun. In 0.10 it read traintimes.pyfun, the name only lowercased. Rename the file, and the compiler emits train_times.py to match.

error: cannot find module `TrainTimes` (expected `train_times.pyfun`), imported by `Main`

A one-word module (import Geometry, read from geometry.pyfun) is unaffected.

Rules the checker now enforces

Each of these was a program that 0.10 accepted and that then failed, or ran the wrong code, when Python ran it. 0.11 reports them as compile errors.

A name is used below the line that defines it

Write a definition above its first use. The compiler reads a file from top to bottom, as Python does.

error: `helper` cannot be used yet: it is defined below this line (move this line below `helper`)

Mutually recursive functions can still call each other in either direction. A value written between two of them can’t call them yet, because the second one doesn’t exist at that point:

error: `is_even` cannot be used yet: it needs `is_odd`, which is defined below this line (move this line below `is_odd`)

Move the value below the last function of the group.

A constructor and a record type have different names

A constructor called Point and a record type called Point both became the Python class Point. Rename one of them.

Some names belong to the compiler

  • A name beginning _pf_ is an error. The compiler writes such names into the Python it emits.
  • Json, JNull, JBool, JInt, JFloat, JStr, JList and JObject are built in, for reading JSON as data. A type or constructor of yours with one of these names needs another.

A function’s own accumulator is pure

A let mut that a function declares and assigns in its own body no longer counts as io, so let pure accepts the accumulator style:

let pure sum_to n =
  let mut acc = 0
  acc <- acc + n
  acc

This breaks one pattern. A function that was io only through its own accumulator is now pure, so it no longer fits a callback arrow declared ->{io}. In an extern, declare the arrow with an effect variable, ->{e}, which accepts a callback with any effects. The error names the exact arrow to write.

Doc comments

Only the ## lines directly above a declaration document it. A ## block with a blank line between it and the next declaration, such as a section banner, is now an ordinary comment. If you spaced a doc comment away from its function, close the gap.

If Python code imports your compiled modules

The emitted Python changed in three ways that Python callers can see.

  • More names gain a trailing underscore. A binding named after a Python built-in the emitted code calls (min, max, all, any, enumerate, format, getattr) or after a module the compiler imports for itself (json, functools, itertools, asyncio) is emitted as max_, json_ and so on, as len and sum already were. A constructor named ValueError, RuntimeError or TimeoutError becomes the class ValueError_.
  • A name bound twice at the top level keeps each binding apart. The last one keeps the name and the earlier one is emitted as _helper.
  • A multi-word module’s file is train_times.py, where it was traintimes.py.

If a tool reads the compiler’s messages

  • Every diagnostic names its file: the location line reads --> shapes.pyfun:3:9.
  • A type variable prints as a, where it printed 'a, and constraints come first: comparison a => a -> a -> bool.
  • A name used above its definition is reported as “helper cannot be used yet: it is defined below this line”, where it said unbound name.

What’s new

0.11 also adds Map and Set literals, in and not in, constructors with named fields, from Module import name, packages, the exn effect, warnings, pyfun test, pyfun fmt, tracebacks in .pyfun lines, typed Python output, and inlay hints and quick fixes in the editor. The 0.11.0 release notes describe each one.