blueprint_book

Contains the BlueprintBook class for easily creating and manipulating Factorio blueprint books.

class BlueprintBook(
label='',
label_color=None,
description='',
icons=NOTHING,
version=NOTHING,
index: ~typing.Annotated[int,
<draftsman.validators._AndValidator object at 0x7436dd5c5660>] | None = None,
item: str = 'blueprint-book',
active_index: ~typing.Annotated[int,
<draftsman.validators._AndValidator object at 0x7436dd5c5660>] = 0,
blueprints: ~draftsman.classes.blueprint_book.BlueprintableList = NOTHING,
*,
extra_keys: dict[str,
~typing.Any] | None = None,
)

Bases: Blueprintable

Factorio Blueprint Book class. Contains a list of Blueprintable objects as well as some of it’s own metadata.

active_index : _AndValidator object at 0x7436dd5c5660>]

Serialized

This attribute is imported/exported from blueprint strings.

The currently selected Blueprintable in the BlueprintBook, or in other words the Blueprintable with the matching index.

blueprints : BlueprintableList

Serialized

This attribute is imported/exported from blueprint strings.

The list of blueprintable objects within this blueprint book. Can also be specified as a regular list:

>>> from draftsman.blueprintable import *
>>> bpb = BlueprintBook()
>>> bpb.blueprints = [Blueprint(), DeconstructionPlanner(), UpgradePlanner()]
>>> assert len(bpb.blueprints) == 3
description : str

Serialized

This attribute is imported/exported from blueprint strings.

The description of the blueprintable. Visible when hovering over it when inside someone’s inventory. Has a maximum size of 500 bytes.

extra_keys : dict[str, Any] | None

Serialized

This attribute is imported/exported from blueprint strings.

Any additional keys that are not recognized by Draftsman when loading from a raw JSON dictionary end up as keys in this attribute. Under normal circumstances, this field should always remain None, indicating that all fields provided were properly translated into the internal Python format.

If there are any values in extra_keys after being imported from a raw JSON dictionary, then (left alone) these values will also be exported back into an output JSON dictionary in order to keep import-export cycles stable. A side effect of this is that users can use this attribute to add additional fields that will end up in the output string, primarily for custom metadata that can be read by other tools:

>>> input_dict = {
...    "name": "wooden-chest",
...    "position": {"x": 0.5, "y": 0.5},
...    "unknown_key": "blah"
... }
>>> container = Container.from_dict(input_dict)
>>> container.extra_keys
{"unknown_key": "blah"}
>>> container.extra_keys["custom"] = "data"
>>> container.to_dict()
{
    "name": "wooden-chest",
    "position": {"x": 0.5, "y": 0.5},
    "unknown_key": "blah",
    "custom": "data"
}

The structure of input keys are preserved, meaning you may have to recurse through keys to find the unknown data:

>>> input_dict = {
...     "name": "wooden-chest",
...     "position": {"x": 0.5, "y": 0.5},
...     "nested": {
...         "dictionary": "value"
...     }
... }
>>> container = Container.from_dict(input_dict)
>>> container.extra_keys
{"nested": {"dictionary": "value"}}

Note

While Draftsman makes an effort to preserve keys that it doesn’t recognize, Factorio itself makes no such effort - so if you create a blueprint string with custom metadata and then import it into the game, that additional data will be stripped and cannot be retrieved when exporting a new string from the game.

icons : list[Icon]

Serialized

This attribute is imported/exported from blueprint strings.

The visible icons of the blueprintable, as shown in the icon in Factorio’s GUI. A max of 4 Icon s are permitted.

Icons can also be specified more succinctly as a simple list of signal names:

>>> from draftsman.blueprintable import Blueprint
>>> blueprint = Blueprint()
>>> blueprint.icons = ["transport-belt"]
>>> blueprint.icons
[Icon(index=0, signal=SignalID(name='transport-belt', type='item', quality='normal'))]
index : uint16 | None

Serialized

This attribute is imported/exported from blueprint strings.

The location of the blueprintable in a parent BlueprintBook. This member is automatically generated if omitted, but can be manually set with this attribute. This attribute has no meaning when the blueprintable is not located inside another blueprint book.

item : str

Serialized

This attribute is imported/exported from blueprint strings.

Always the name of the corresponding Factorio item to this blueprintable instance. Read only.

label : str

Serialized

This attribute is imported/exported from blueprint strings.

The user given name (title) of the blueprintable.

label_color : Color | None

Serialized

This attribute is imported/exported from blueprint strings.

The Color of the Blueprint’s label.

property root_item : 'blueprint_book'

Serialized

This attribute is imported/exported from blueprint strings.

The “root” key of this Blueprintable’s dictionary form. For example, blueprints have the root_item key “blueprint”:

{
    "blueprint": { # <- this is the "root_item"
        ...
    }
}

All keys (except for index) are contained within this sub- dictionary.

version : uint64

Serialized

This attribute is imported/exported from blueprint strings.

The version of Factorio the Blueprint was created in.

The Blueprint version is a 64-bit integer, which is a bitwise-OR of four 16-bit numbers. You can interpret this number more clearly by decoding it with draftsman.utils.decode_version(), or you can use the functions version_tuple() or version_string() which will give you a more readable output. This version number defaults to the version of Factorio of Draftsman’s environment.

The version can be set either a 64-bit int in the format above, or as a sequence of ints (usually a list or tuple) which is then encoded into the combined representation. The sequence is defined as: [major_version, minor_version, patch, development_release] with patch and development_release defaulting to 0.

Example:

>>> from draftsman.blueprintable import Blueprint
>>> blueprint = Blueprint()
>>> blueprint.version = (1, 0) # version 1.0.0.0
>>> assert blueprint.version == 281474976710656
>>> assert blueprint.version_tuple() == (1, 0, 0, 0)
>>> assert blueprint.version_string() == "1.0.0.0"
classmethod from_dict(
d: dict,
version: tuple[int, ...] | None = None,
) Self

Attempts to construct a new instance of this class from a Python dictionary in JSON format.

Parameters:
d: dict

The dictionary to interpret.

version: tuple[int, ...] | None = None

The Factorio version that the input data is compliant with.

The given version tuple will automatically attempt to grab the closest applicable converter - meaning that specifying a version of (1, 1, 96) will use the 1.0 converter, and a version of (2, 0, 32) will use the 2.0 converter.

If no version is provided, it will default to current environment’s Factorio version, or to draftsman.DEFAULT_FACTORIO_VERSION if unable to read the current environment.

classmethod from_string(string: str)

Creates a Blueprintable with the contents of string.

Raises UnknownKeywordWarning if there are any unrecognized keywords in the blueprint string for this particular blueprintable.

Parameters:
string: str

The Factorio-encoded blueprint string to decode.

Raises:
to_dict(
version: tuple[int, ...] | None = None,
exclude_none: bool = True,
exclude_defaults: bool = True,
) dict

Export this object to a JSON dictionary, usually directly prior to encoding into the compressed blueprint string format.

Parameters:
version: tuple[int, ...] | None = None

Which Factorio version format this entity should be exported with. The same Draftsman object can be converted to many version-specific output dictionaries, each of which may have different structures.

The given version tuple will automatically attempt to grab the closest applicable converter - meaning that specifying a version of (1, 1, 96) will use the 1.0 converter, and a version of (2, 0, 32) will use the 2.0 converter.

If no version is provided, it will default to current environment’s Factorio version, or to draftsman.DEFAULT_FACTORIO_VERSION if unable to read the current environment.

exclude_none: bool = True

Whether or not None properties should be omitted from the output string. For certain properties this option has no effect, as they either must always be present or never be present if None.

exclude_defaults: bool = True

Whether or not to exclude properties that are equivalent to their default values. Including these values in the generated output is redundant as Factorio will populate them automatically, but it is useful to disable for debug/illustation purposes.

to_string(version: tuple[int] | None = None) str

Returns this object as an encoded Factorio blueprint string.

Returns:

The zlib-compressed, base-64 encoded string.

Example:

>>> from draftsman.blueprintable import (
...     Blueprint, DeconstructionPlanner, UpgradePlanner, BlueprintBook
... )
>>> Blueprint(version=(1, 0)).to_string()
'0eNqrVkrKKU0tKMrMK1GyqlbKLEnNVbJCEtNRKkstKs7Mz1OyMrIwNDE3sTQ3Mzc0MDM1q60FAHmVE1M='
>>> DeconstructionPlanner(version=(1, 0)).to_string()
'0eNqrVkpJTc7PKy4pKk0uyczPiy/ISczLSy1SsqpWyixJzVWyQlOgC1Ogo1SWWlQMFFGyMrIwNDE3sTQ3Mzc0MDM1q60FAHp9Hf0='
>>> UpgradePlanner(version=(1, 0)).to_string()
'0eNqrViotSC9KTEmNL8hJzMtLLVKyqlbKLEnNVbKCyejCZHSUylKLijPz85SsjCwMTcxNLM3NzA0NzEzNamsBqdIX5Q=='
>>> BlueprintBook(version=(1, 0)).to_string()
'0eNqrVkrKKU0tKMrMK4lPys/PVrKqVsosSc1VskJI6IIldJTKUouKM/PzlKyMLAxNzE0szc3MDQ3MTM10lBKTSzLLUuMz81JSK5SsDGprATINHQI='
validate(
mode: ValidationMode = ValidationMode.STRICT,
) ValidationResult

Validates the called object against it’s known format.

Example:

>>> import draftsman
>>> from draftsman.constants import ValidationMode
>>> from draftsman.entity import Container
>>> from draftsman.error import DataFormatError
>>> c = Container("wooden-chest")
>>> with draftsman.validators.set_mode(ValidationMode.DISABLED):
...     c.bar = "incorrect"
>>> try:
...     c.validate().reissue_all()
... except DataFormatError as e:
...     print("wrong!")
wrong!
Parameters:
mode: ValidationMode = ValidationMode.STRICT

How strict to be when valiating the object, corresponding to the number and type of errors and warnings returned.

Returns:

A ValidationResult object, which contains all errors and warnings from the validation pass.

version_string() str

Returns the version of the Blueprintable in human-readable string.

Returns:

a str of 4 version numbers joined by a ‘.’ character.

Example:

>>> from draftsman.blueprintable import Blueprint
>>> blueprint = Blueprint(version=(1, 2, 3))
>>> blueprint.version_string()
'1.2.3.0'
version_tuple() tuple[~typing.Annotated[int, <draftsman.validators._AndValidator object at 0x7436dd5c5660>], ~typing.Annotated[int, <draftsman.validators._AndValidator object at 0x7436dd5c5660>], ~typing.Annotated[int, <draftsman.validators._AndValidator object at 0x7436dd5c5660>], ~typing.Annotated[int, <draftsman.validators._AndValidator object at 0x7436dd5c5660>]]

Returns the version of the Blueprintable as a 4-length tuple.

Returns:

A 4 length tuple in the format (major, minor, patch, dev_ver).

Example:

>>> from draftsman.blueprintable import Blueprint
>>> blueprint = Blueprint(version=281474976710656)
>>> blueprint.version_tuple()
(1, 0, 0, 0)
class BlueprintableList(
initlist: Sequence[dict | Blueprintable] = [],
)

Bases: MutableSequence

List of Blueprintable instances.

append(value)

S.append(value) – append value to the end of the sequence

clear() None -- remove all items from S
count(value) integer -- return number of occurrences of value
extend(values)

S.extend(iterable) – extend sequence by appending elements from the iterable

index(
value[,
start[,
stop,]]
) integer -- return first index of value.

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

insert(
idx: int,
value: Blueprintable,
)

S.insert(index, value) – insert value before index

pop(
[index,]
) item -- remove and return item at index (default last).

Raise IndexError if list is empty or index is out of range.

remove(value)

S.remove(value) – remove first occurrence of value. Raise ValueError if the value is not present.

reverse()

S.reverse() – reverse IN PLACE