Skip to content

Version 0.1.0 is a first version, for trial. See what is not proven →

bogolang
FR

← Documentation

The language

The class rule, types on every line, what differs from Python, the new statements, editions.

All documentation pages

This page describes Bogolang itself: how a file is laid out, what "a type on every line" means, what differs from Python, and the statements Bogolang adds. The built-in commands are on the pages of each group, and every name is in reference.md.

Bogolang is Python 3.15 with additions for network and telecom work. A .bogo file is read, checked and run on a Python 3.15 engine that Bogolang carries. Nothing is compiled to native code. The check runs before every run, and a program with a mistake does not start.

How a file is laid out

The top of a .bogo file holds only:

  • the line edition 2027, as the first line that is not blank and not a comment;
  • a describing text (a docstring), as the first statement;
  • imports: import x, from x import y, from __future__ import ..., and lazy import;
  • classes.

Comments may stand anywhere. Every other statement at the top is refused, one message per statement. This covers a function, an assignment, a call, if, for, try, with and a type alias:

top.bogo:3:1: error: code must be inside a class
    x = 1
    ^
    Only imports and classes stand at the top of a file. Put this line in a method of a class.

The body of a class holds only a describing text as its first statement, ..., pass, fields (with or without a written type), methods (also async), classes, type aliases, and the two Bogolang blocks rule and on. A loose statement in a class body is refused, where Python would run it:

top.bogo:6:5: error: this line cannot stand in the body of a class
    print("hi")
    ^
    A class holds fields, methods, classes, rule and on. Put this line in a method.

The rule holds for every class, also one inside a class or inside a method. Inside a method all of Python and all the Bogolang statements are valid, except on.

Everything Python offers for classes stays: inheritance, decorators, @dataclass, Enum, Protocol, properties, class methods.

Where a program starts

A program starts in the class whose name matches the name of the file. Only letters and digits are compared, in small letters: link_check.bogo, LinkCheck.bogo and link-check.bogo all match class LinkCheck. A file name that starts with a digit gets an underscore in front: 1st_check.bogo matches class _1stCheck.

main is written exactly so: the decorator @staticmethod and no other, not async, one input named args of type list[str], no default, and the result type None. args holds the words typed after the file name.

Bogolang
edition 2027
"""Says which routers answer."""


class LinkCheck:
    """Pings each router twice."""

    routers: list[IP] = [192.0.2.1, 192.0.2.2]

    @staticmethod
    def main(args: list[str]) -> None:
        for r in LinkCheck.routers:
            print(r, ping(r, count=2))

Inside a method, a field of the class is reached through the class, LinkCheck.routers, or through self, as in Python.

When the program runs, the file is first read from top to bottom: the fields get their values, the rules are registered and the listeners of on open. Then main is called.

The start class is asked for only of the file that is run (bogo run, bogo FILE.bogo, bogo pack). A file with no start class is a library: other files import its classes, and bogo check and bogo test accept it. bogo run link_check.bogo on it says link_check.bogo:1:1: error: this file has no class LinkCheck with a main method, followed by the four lines of a start class. A class with no main gets class LinkCheck has no main method, and a main written another way gets main is not written the way a program starts.

Tests

A test is a method whose name starts with test_, in a class whose name starts with Test, at the top of a file. It takes self only and returns nothing. It passes when it ends with no error, and uses assert as in Python.

  • In a project, test files are tests/test_*.bogo, and bogo test runs them all.
  • A program may also hold its own Test classes. bogo test FILE runs those of one file.
  • Each test runs on a new object of its class, so a field changed by one test is fresh for the next. Tests run in the order they are written.
  • A test with another input fails with: a test takes self only. Write it as: def test_name(self) -> None:.
  • A test_ method in a class whose name does not start with Test is not run.
Bogolang
edition 2027


class Plan:
    @staticmethod
    def halves(n: Net) -> list[Net]:
        return n.split(n.prefix + 1)


class TestPlan:
    def test_a_24_gives_two_25(self) -> None:
        assert Plan.halves(192.0.2.0/24) == [192.0.2.0/25, 192.0.2.128/25]

tools.md gives the options of bogo test.

Types on every line

Every value in Bogolang code has a type known before the program runs. In practice:

  • Every function and method says the type of each input and of its result.
  • A variable takes the type of its first value. net = 192.0.2.0/24 is a Net and stays one. Giving it a text later is an error.
  • A variable whose first value says nothing of its type is declared: rows: list[str] = [].
  • Nothing may have the type "unknown". A written Any is refused.

Writing the type of every variable is allowed too. The examples use both styles.

Bogolang
used: list[Net] = [192.0.2.0/26]
free = next_free(192.0.2.0/24, 26, used)
total = free.size - 2
print(free, total)

What the check says for each case:

Mistake Message
A method with no types this method has no types
rows = [] rows needs a type, with the hint For example: rows: list[<type>] = ...
net = 192.0.2.0/24, then net = "x" this value is a str, but the variable is declared as Net
A value from code with no types, such as json.loads(...) the type of this value is unknown

Values from code with no types

A Python package that has types is used as it is. A value from a package with no types gets its type on the line where it enters:

Bogolang
import json


class Read:
    @staticmethod
    def count(text: str) -> int:
        n: int = json.loads(text)
        return n

That line is also tested when the program runs: if the value is not an int, the program stops there with a clear message. For a container such as list[int] only the outside is tested. A line name: type = value in a class body is not tested when the program runs, so such a value enters in a method.

Without the type, the check says:

kinds.bogo:8:16: error: the type of this value is unknown
    data = json.loads("{}")
           ^^^^^^^^^^^^^^^^
    It comes from code that has no types. Give it a type on the line where it enters,
    for example:  count: int = ...

A lambda given as key= to max, min, sorted or .sort passes the check when it names only its own parameter and built-in names, as in key=lambda r: r.loss. One that names a variable from outside is refused. The hint says what to write: a small method with types, given by its name.

Untyped

An object from a package with no types, such as a connection object, cannot be given a real type. Declare it Untyped. It may then be called, read from, written to, indexed, looped over and used in a with block. Each result gets its own type on a line of its own:

```bogo skip conn: Untyped = oldpackage.connect("192.0.2.1") banner: str = conn.read_banner() conn.close()


Refused before the run: passing an `Untyped` value where a type is asked, arithmetic on it,
and giving it to a variable that already has a type. `bogo check` lists every line that holds
an `Untyped` object, for review, after `no errors`. What is done with the object itself is
checked only when the program runs.

## What differs from Python

| Python | Bogolang |
|---|---|
| Any statement at the top of a file | Only imports and classes (see above) |
| Loose statements in a class body | Refused |
| A program starts at the top of the file | It starts in `main` of the class named after the file |
| Types are optional | Types are required, and checked before every run |
| `192.0.2.1` is a syntax error | An `IP` literal. Also subnets, MACs and units ([types-and-units.md](types-and-units.md)) |
| `ping` and the rest must be imported | The built-in names are there in every file, with no import |
| `python file.py` | `bogo run file.bogo` or `bogo file.bogo` |

A program may reuse a built-in name for something of its own, as it may reuse a Python
built-in. Inside a method, a local name always wins. One case is left: a file that defines its
own `Net` or `Power` cannot also write the matching literal.

The new words (`where`, `parallel`, `change`, `apply`, `rollback`, `verify`, `every`, `wait`,
`retry`, `only`, `watch`, `alert`, `on`, `rule`) are special only in the places shown below.
Anywhere else they are ordinary names.

Limits of the reader: a literal inside the `{}` of an f-string is not recognised (put the
value in a variable first), and the header line of each new statement must be on one line.

## The new statements

| Statement | Where it is written | Page |
|---|---|---|
| `for ... where ... parallel` | In a method | below |
| `wait until`, `retry`, `every`, `only between` | In a method | below |
| `watch`, `alert when` | In a method | [watch-listen.md](watch-listen.md) |
| `change on` | In a method | [changes.md](changes.md) |
| `rule` | In a class body or in a method | [config-audit-templates.md](config-audit-templates.md) |
| `on syslog`, `on trap`, `on netflow` | In a class body only | [watch-listen.md](watch-listen.md) |

### `for ... where ... parallel`

`where` skips the items for which the condition is false. `parallel N` runs the block for up
to N items at the same time. Either may be used alone.

```bogo
devices: list[Device] = inventory("devices.csv")
for d in devices where d.role == "core" parallel 4:
    with ssh(d) as s:
        print(d.name, s.show("version").text.splitlines()[0])
for f in last_failures():
    print(f)

Inside a parallel block:

  • A variable given a value inside the block belongs to that one run. Variables from outside can be read, and a list from outside can be added to.
  • break and return are refused by the check. continue skips the current item.
  • What a run prints is held and shown as one piece, in the order of the list.
  • An error in one run stops that run only. After the loop, last_failures() gives the items that failed, with the reason. If the program does not read it, a summary is printed at the end and the run ends with a failure code.

A limit: the check does not yet refuse a program that reads a variable of the block after the loop. Such a program stops when it runs.

wait until

Tests a condition every 5 seconds, or every the time after every, until it is true. An error if the timeout passes first.

Bogolang
wait until tcping(192.0.2.1, 22) timeout 2min every 10s

retry

Runs the block. On an error it runs it again, up to the number of tries in all, with an optional pause. After the last try the last error is raised. A change inside a retry is refused: a failed change is rolled back, and the reason is found before it is sent again.

Bogolang
retry 3 every 5s:
    r: PingResult = ping(192.0.2.1, count=2)
    print(r)

every

Runs the block, waits until the period has passed since the start of that run, and repeats until the program is stopped (Ctrl+C) or the block uses break.

Bogolang
turns = 0
every 1min:
    print(now(), ping(192.0.2.1, count=3))
    turns += 1
    if turns == 10:
        break

only between: time windows

Runs the block only when the time of day in a zone is inside the window. Outside it, the program stops with an error. Under --dry it prints a line and skips the block instead. A window may cross midnight. The zone is a plain name such as UTC, or a quoted name such as "Europe/Paris".

Bogolang
only between time"22:00" and time"04:00" UTC:
    print("inside the maintenance window")

Outside the window the error names the window and the time it is now in that zone.

watch and alert when

watch EXPR every PERIOD [for TIME] draws the value live in the terminal until it is stopped or the time is over. alert when CONDITION for TIME [per KEY] [as NAME]: runs its block once when the condition has been true for that long, and once when it clears. It stands inside an every block; inside a loop it needs per, so each item keeps its own memory.

Bogolang
hosts: list[IP] = [192.0.2.10, 198.51.100.20]
watch ping(192.0.2.10, count=1).avg every 1s for 1min
every 1min:
    for h in hosts:
        r: PingResult = ping(h, count=4)
        alert when r.loss > 5pct for 3min per h as a:
            print(h, "raised" if a.raised else "cleared", a.lasted)

change on

A change to a device, with the lines that undo it. A change with no rollback is refused by the check. changes.md gives the steps it follows.

Bogolang
sw: Device = Device(name="access-sw1", ip=192.0.2.21, platform="iosxe")
port: str = "GigabitEthernet1/0/5"
change on sw revert_after 5min:
    apply:
        interface {port}
         description CAMERA-12
    rollback:
        interface {port}
         no description
    verify:
        "CAMERA-12" in show(f"interfaces {port} description")

The lines under apply and rollback are device text, sent as written. {name} puts a value in the line; {{ and }} send real braces.

rule and on

A rule is a list of tests, one per line, each true or false for one device. audit(...) runs the rules. An on block listens for syslog, traps or NetFlow, and runs for each event. It is written in a class body only; its listener opens when the class is read, before main.

Bogolang
edition 2027


class Watcher:
    devices: list[Device] = [Device(name="core-sw1", ip=192.0.2.1, platform="iosxe")]

    rule "no telnet on the vty lines" for d where d.role != "server":
        not config.has("transport input telnet")

    on syslog port 5514 from devices matching "UPDOWN" as e:
        print(e.received, e.device, e.message)

    @staticmethod
    def main(args: list[str]) -> None:
        for c in listen(10min):
            print(c.received, "events")

The listener opens on every address of the computer unless address names one: on syslog port 5514 address 192.0.2.50 from devices as e:. An on block may not hold a change. Inside the block, a field of the class is reached through the class.

Editions

An edition fixes the meaning of the language. A newer Bogolang runs every older edition with the meaning it had. A change that would alter what existing code does, or remove something, comes only in a new edition, after one edition of warning.

  • There is one edition today: 2027.
  • A single file states it on its first line: edition 2027.
  • A project states it in bogo.toml, and its files need not repeat it.
  • A single file with no edition line runs with the newest edition and gets a warning: this file does not say which edition it is written for, with the line to add.
  • An unknown edition is an error that lists the known ones.

Python 3.15

The engine is Python 3.15, and its new syntax is usable inside the class rule. Tried and tested in Bogolang: lazy import, lazy from ... import, unpacking inside a list, set and dictionary comprehension, and the built-in frozendict.

Bogolang
edition 2027
lazy import json


class Newer:
    groups: list[list[int]] = [[1, 2], [3]]

    @staticmethod
    def main(args: list[str]) -> None:
        flat = [*g for g in Newer.groups]
        merged = {**d for d in [{"a": 1}, {"b": 2}]}
        fixed = frozendict(a=1, b=2)
        print(flat, merged, fixed["a"], json.dumps(flat))

A lazy import of another .bogo file counts like a plain import: the file is checked with the program.

Python packages

Every Python package works, imported as it is. In a project, add one with bogo add, which installs it into the environment of the project and writes it in bogo.toml and bogo.lock:

bogo add requests
bogo add "netaddr>=1.3"
bogo add requests --from FOLDER

--from FOLDER installs from package files in a folder, with no internet. bogo remove NAME takes a package out again. A program then imports it:

```bogo skip import requests

class Fetch: @staticmethod def main(args: list[str]) -> None: r = requests.get("https://192.0.2.80/status", timeout=5) code: int = r.status_code print(code) ```

The packages of the built-in commands (Netmiko, pysnmp and the others) are part of Bogolang; a project does not add them. Plain .py files beside a program can be imported too. The class rule is for .bogo files only.

Bogolang's own types are ordinary Python objects. .to_python() on an IP or a Net gives the object of Python's ipaddress module, for a package that wants one.