entity_list

class EntityList(
parent: Collection = None,
initlist: list[EntityLike] | None = [],
copy: bool = True,
)

Bases: Exportable, MutableSequence

Custom object for storing sequences of EntityLike.

Contains all the functionality of a normal list. Adds the ability to index with id strings, as well as extra framework for interfacing with Collection classes.

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.

append(
name: str | EntityLike,
copy: bool = True,
merge: bool = False,
**kwargs,
) EntityLike

Appends the EntityLike to the end of the sequence. Returns a reference to the appended entity, if successful.

Supports an optional shorthand where you can specify the string name of an Entity as entity and any keyword arguments, which are appended to the constructor of that entity.

If copy is specified, a deepcopy of the passed in entity is created. If any additional keyword arguments are specified alongside, the attributes of that newly copied entity are overwritten with them.

Parameters:
name: str | EntityLike

Either a string reprenting the name of an Entity, or an EntityLike instance.

copy: bool = True

Whether or not to create a copy of the passed in EntityLike. If name is in string shorthand, this option is ignored and a new instance is always created.

merge: bool = False

Whether or not to merge entities of the same type at the same position. Merged entities share non-overlapping attributes and prefer the attributes of the last entity added. Useful for merging things like rails or power-poles on the edges of tiled blueprints.

**kwargs

Any other keyword arguments to pass to the entity instance. This is used primarily when constructing a new entity from a string name, but can also be used to overwrite certain attributes of a passed in EntityLike before adding it to the EntityList.

Example:

blueprint = Blueprint()
assert isinstance(blueprint.entities, EntityList)

# Append Entity instance
blueprint.entities.append(Container("steel-chest"))
assert blueprint.entities[-1].name == "steel-chest"

# Append shorthand
blueprint.entities.append("wooden-chest", tile_position=(1, 1))
assert blueprint.entities[-1].name == "wooden-chest"
assert blueprint.entities[-1].tile_position == {"x": 1, "y": 1}

# Key indexing
blueprint.entities.append(
    TransportBelt(id = "some_id", tile_position=(1, 0))
)
assert isinstance(blueprint.entities["some_id"], TransportBelt)

# No copy
inserter = Inserter("fast-inserter", tile_position=(0, 1))
blueprint.entities.append(inserter, copy=False)
inserter.stack_size_override = 1
assert inserter is blueprint.entities[-1]
assert blueprint.entities[-1].stack_size_override == 1
check_entitylike(entitylike: EntityLike)

A set of universal checks that all EntityLike`s have to follow if they are to be added to this ``EntityList`.

Raises HiddenEntityWarning if the EntityLike being checked is marked as hidden.

Parameters:
entitylike: EntityLike

EntityLike instance to check.

Raises:
  • TypeError – If entitylike is not an EntityLike instance.

  • DuplicateIDError – If entitylike.id is already taken in the EntityList.

clear() None -- remove all items from S
count(value) integer -- return number of occurrences of value
difference(
other: EntityList,
) EntityList

TODO

extend(
entities: list[str | EntityLike],
copy: bool = True,
merge: bool = False,
) None

Extends this list with the list provided. Computationally the same as appending one element at a time.

Parameters:
copy: bool = True

Whether or not to insert a copy of each element.

merge: bool = False

Whether or not to merge each element, if possible.

Example:

blueprint = Blueprint()
assert isinstance(blueprint.entities, EntityList)

# Append Entity instance
blueprint.entities.extend([Container("steel-chest"), Container("wooden-chest", tile_position=(1, 1)])
assert blueprint.entities[-2].name == "steel-chest"
assert blueprint.entities[-1].name == "wooden-chest"
assert blueprint.entities[-1].tile_position == {"x": 1, "y": 1}
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.

get_pair(item: int | str) tuple[int, str]

Takes either an index or a key, finds the converse entry associated with it, and returns them both as a pair.

Parameters:
item: int | str

Either an integer index or a string key.

Returns:

A tuple of the format (index, key).

Raises:

KeyError – If key item is not found in the key mapping dictionaries in the EntityList.

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,
name: str | EntityLike,
copy: bool = True,
merge: bool = False,
**kwargs,
) EntityLike

Inserts an EntityLike into the sequence.

Supports an optional shorthand where you can specify the string name of an Entity as entity and any keyword arguments, which are appended to the constructor of that entity.

If copy is specified, a deepcopy of the passed in entity is created. If any additional keyword arguments are specified alongside, the attributes of that newly copied entity are overwritten with them.

Parameters:
idx: int

The integer index to put the EntityLike.

name: str | EntityLike

Either a string reprenting the name of an Entity, or an EntityLike instance.

copy: bool = True

Whether or not to create a copy of the passed in EntityLike. If name is a string name of an entity, this option is ignored and a new instance is always created.

merge: bool = False

Whether or not to merge entities of the same type at the same position. Merged entities share non-overlapping attributes and prefer the attributes of the last entity added. Useful for merging things like rails or power-poles on the edges of tiled blueprints.

**kwargs

Any other keyword arguments to pass to the entity instance. This is used primarily when constructing a new entity from a string name, but can also be used to overwrite specific attributes of a passed in EntityLike before adding it to the EntityList.

Example:

blueprint = Blueprint()
assert isinstance(blueprint.entities, EntityList)

# Insert Entity instance
blueprint.entities.insert(0, Container("steel-chest"))
assert blueprint.entities[0].name == "steel-chest"

# Insert shorthand
blueprint.entities.insert(1, "wooden-chest", tile_position=(1, 1))
assert blueprint.entities[1].name == "wooden-chest"
assert blueprint.entities[1].tile_position == {"x": 1, "y": 1}

# Key indexing
blueprint.entities.insert(
    0, TransportBelt(id = "some_id", tile_position=(1, 0))
)
assert isinstance(blueprint.entities["some_id"], TransportBelt)

# No copy
inserter = Inserter("fast-inserter", tile_position=(0, 1))
blueprint.entities.insert(0, inserter, copy=False)
inserter.stack_size_override = 1
assert inserter is blueprint.entities[0]
assert blueprint.entities[0].stack_size_override == 1
intersection(
other: EntityList,
) EntityList

TODO

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

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

recursive_remove(item: EntityLike) None

Removes an EntityLike from the EntityList. Recurses through any subgroups to see if item is there, removing the root-most entity first.

Raises:

ValueError – If unable to locate the passed in entity anywhere in the EntityList.

remove(value)

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

reverse()

S.reverse() – reverse IN PLACE

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.

union(
other: EntityList,
) EntityList

TODO

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.