See also

For usage of the query features see the tutorial: Tutorial for Getting Data from DXF Files

Entity Query String

QueryString := EntityQuery ("[" AttribQuery "]" "i"?)*

The query string is the combination of two queries, first the required entity query and second the optional attribute query, enclosed in square brackets, append 'i' after the closing square bracket to ignore case for strings.

Entity Query

The entity query is a whitespace separated list of DXF entity names or the special name '*'. Where '*' means all DXF entities, exclude some entity types by appending their names with a preceding ! (e.g. all entities except LINE = '* !LINE'). All DXF names have to be uppercase.

Attribute Query

The optional attribute query is a boolean expression, supported operators are:

  • not (!): !term is true, if term is false

  • and (&): term & term is true, if both terms are true

  • or (|): term | term is true, if one term is true

  • and arbitrary nested round brackets

  • append (i) after the closing square bracket to ignore case for strings

Attribute selection is a term: “name comparator value”, where name is a DXF entity attribute in lowercase, value is a integer, float or double quoted string, valid comparators are:

  • == equal “value”

  • != not equal “value”

  • < lower than “value”

  • <= lower or equal than “value”

  • > greater than “value”

  • >= greater or equal than “value”

  • ? match regular expression “value”

  • !? does not match regular expression “value”

Query Result

The EntityQuery class is the return type of all query() methods. EntityQuery contains all DXF entities of the source collection, which matches one name of the entity query AND the whole attribute query. If a DXF entity does not have or support a required attribute, the corresponding attribute search term is False.

examples:

  • LINE[text ? ".*"]: always empty, because the LINE entity has no text attribute.

  • LINE CIRCLE[layer=="construction"]: all LINE and CIRCLE entities with layer == "construction"

  • *[!(layer=="construction" & color<7)]: all entities except those with layer == "construction" and color < 7

  • *[layer=="construction"]i, (ignore case) all entities with layer == "construction" | "Construction" | "ConStruction"

EntityQuery Class

class ezdxf.query.EntityQuery

The EntityQuery class is a result container, which is filled with DXF entities matching the query string. It is possible to add entities to the container (extend), remove entities from the container and to filter the container. Supports the standard Python Sequence methods and protocols. Does not remove automatically destroyed entities (entities deleted by calling method destroy()), the method purge() has to be called explicitly to remove the destroyed entities.

first

First entity or None.

last

Last entity or None.

__len__() int

Returns count of DXF entities.

__getitem__(item)

Returns DXFEntity at index item, supports negative indices and slicing. Returns all entities which support a specific DXF attribute, if item is a DXF attribute name as string.

__setitem__(key, value)

Set the DXF attribute key for all supported DXF entities to value.

__delitem__(key)

Discard the DXF attribute key from all supported DXF entities.

__eq__(other)

Equal selector (self == other). Returns all entities where the selected DXF attribute is equal to other.

__ne__(other)

Not equal selector (self != other). Returns all entities where the selected DXF attribute is not equal to other.

__lt__(other)

Less than selector (self < other). Returns all entities where the selected DXF attribute is less than other.

Raises:

TypeError – for vector based attributes like center or insert

__le__(other)

Less equal selector (self <= other). Returns all entities where the selected DXF attribute is less or equal other.

Raises:

TypeError – for vector based attributes like center or insert

__gt__(other)

Greater than selector (self > other). Returns all entities where the selected DXF attribute is greater than other.

Raises:

TypeError – for vector based attributes like center or insert

__ge__(other)

Greater equal selector (self >= other). Returns all entities where the selected DXF attribute is greater or equal other.

Raises:

TypeError – for vector based attributes like center or insert

match(pattern: str) EntityQuery

Returns all entities where the selected DXF attribute matches the regular expression pattern.

Raises:

TypeError – for non-string based attributes

__or__(other)

Union operator, see union().

__and__(other)

Intersection operator, see intersection().

__sub__(other)

Difference operator, see difference().

__xor__(other)

Symmetric difference operator, see symmetric_difference().

__iter__() Iterator[DXFEntity]

Returns iterable of DXFEntity objects.

purge() EntityQuery

Remove destroyed entities.

extend(entities: Iterable[DXFEntity], query: str = '*') EntityQuery

Extent the EntityQuery container by entities matching an additional query.

remove(query: str = '*') EntityQuery

Remove all entities from EntityQuery container matching this additional query.

query(query: str = '*') EntityQuery

Returns a new EntityQuery container with all entities matching this additional query.

Raises:

pyparsing.ParseException – query string parsing error

groupby(dxfattrib: str = '', key: Callable[[DXFEntity], Hashable] | None = None) dict[Hashable, list[DXFEntity]]

Returns a dict of entity lists, where entities are grouped by a DXF attribute or a key function.

Parameters:
  • dxfattrib – grouping DXF attribute as string like 'layer'

  • key – key function, which accepts a DXFEntity as argument, returns grouping key of this entity or None for ignore this object. Reason for ignoring: a queried DXF attribute is not supported by this entity

filter(func: Callable[[DXFEntity], bool]) EntityQuery

Returns a new EntityQuery with all entities from this container for which the callable func returns True.

Build your own operator to filter by attributes which are not DXF attributes or to build complex queries:

result = msp.query().filter(
    lambda e: hasattr(e, "rgb") and e.rbg == (0, 0, 0)
)
union(other: EntityQuery) EntityQuery

Returns a new EntityQuery with entities from self and other. All entities are unique - no duplicates.

intersection(other: EntityQuery) EntityQuery

Returns a new EntityQuery with entities common to self and other.

difference(other: EntityQuery) EntityQuery

Returns a new EntityQuery with all entities from self that are not in other.

symmetric_difference(other: EntityQuery) EntityQuery

Returns a new EntityQuery with entities in either self or other but not both.

Extended EntityQuery Features

The [] operator got extended features in version 0.18, until then the EntityQuery implemented the __getitem__() interface like a sequence to get entities from the container:

result = msp.query(...)
first = result[0]
last = result[-1]
sequence = result[1:-2]  # returns not an EntityQuery container!

Now the __getitem__() function accepts also a DXF attribute name and returns all entities which support this attribute, this is the base for supporting queries by relational operators. More on that later.

The __setitem__() method assigns a DXF attribute to all supported entities in the EntityQuery container:

result = msp.query(...)
result["layer"] = "MyLayer"

Entities which do not support an attribute are silently ignored:

result = msp.query(...)
result["center"] = (0, 0)  # set center only of CIRCLE and ARC entities

The __delitem__() method discards DXF attributes from all entities in the EntityQuery container:

result = msp.query(...)
# reset the layer attribute from all entities in container result to the
# default layer "0"
del result["layer"]

Descriptors for DXF Attributes

For some basic DXF attributes exist descriptors in the EntityQuery class:

  • layer: layer name as string

  • color: AutoCAD Color Index (ACI), see ezdxf.colors

  • linetype: linetype as string

  • ltscale: linetype scaling factor as float value

  • lineweight: Lineweights

  • invisible: 0 if visible 1 if invisible, 0 is the default value

  • true_color: true color as int value, see ezdxf.colors, has no default value

  • transparency: transparency as int value, see ezdxf.colors, has no default value

A descriptor simplifies the attribute access through the EntityQuery container and has auto-completion support from IDEs:

result = msp.query(...)
# set attribute of all entities in result
result.layer = "MyLayer"
# delete attribute from all entities in result
del result.layer
# and for selector usage, see following section
assert len(result.layer == "MyLayer") == 1

Relational Selection Operators

The attribute selection by __getitem__() allows further selections by relational operators:

msp.add_line((0, 0), (1, 0), dxfattribs={"layer": "MyLayer})
lines = msp.query("LINE")
# select all entities on layer "MyLayer"
entities = lines["layer"] == "MyLayer"
assert len(entities) == 1

# or select all entities except the entities on layer "MyLayer"
entities = lines["layer"] != "MyLayer"

These operators work only with real DXF attributes, for instance the rgb attribute of graphical entities is not a real DXF attribute either the vertices of the LWPOLYLINE entity.

The selection by relational operators is case insensitive by default, because all names of DXF table entries are handled case insensitive. But if required the selection mode can be set to case sensitive:

lines = msp.query("LINE")
# use case sensitive selection: "MyLayer" != "MYLAYER"
lines.ignore_case = False
entities = lines["layer"] == "MYLAYER"
assert len(entities) == 0

# the result container has the default setting:
assert entities.ignore_case is True

Supported selection operators are:

  • == equal “value”

  • != not equal “value”

  • < lower than “value”

  • <= lower or equal than “value”

  • > greater than “value”

  • >= greater or equal than “value”

The relational operators <, >, <= and >= are not supported for vector-based attributes such as center or insert and raise a TypeError.

Note

These operators are selection operators and not logic operators, therefore the logic operators and, or and not are not applicable. The methods union(), intersection(), difference() and symmetric_difference() can be used to combine selection. See section Query Set Operators and Build Own Filters.

Regular Expression Selection

The EntityQuery.match() method returns all entities where the selected DXF attribute matches the given regular expression. This methods work only on string based attributes, raises TypeError otherwise.

From here on I use only descriptors for attribute selection if possible.

msp.add_line((0, 0), (1, 0), dxfattribs={"layer": "Lay1"})
msp.add_line((0, 0), (1, 0), dxfattribs={"layer": "Lay2"})
lines = msp.query("LINE")

# select all entities at layers starting with "Lay",
# selection is also case insensitive by default:
assert len(lines.layer.match("^Lay.*")) == 2

Build Own Filters

The method EntityQuery.filter can be used to build operators for none-DXF attributes or for complex logic expressions.

Find all MTEXT entities in modelspace containing “SearchText”. All MText entities have a text attribute, no need for a safety check:

mtext = msp.query("MTEXT").filter(lambda e: "SearchText" in e.text)

This filter checks the non-DXF attribute rgb. The filter has to check if the rgb attributes exist to avoid exceptions, because not all entities in modelspace may have the rgb attribute e.g. the DXFTagStorage entities which preserve unknown DXF entities:

result = msp.query().filter(
    lambda e: hasattr(e, "rgb") and e.rgb == (0, 0, 0)
)

Build 1-pass logic filters for complex queries, which would require otherwise multiple passes:

result = msp.query().filter(lambda e: e.dxf.color < 7 and e.dxf.layer == "0")

Combine filters for more complex operations. The first filter passes only valid entities and the second filter does the actual check:

def validator(entity):
    return True  # if entity is valid and has all required attributes

def check(entity):
    return True  # if entity passes the attribute checks

result = msp.query().filter(validator).filter(check)

Query Set Operators

The | operator or EntityQuery.union() returns a new EntityQuery with all entities from both queries. All entities are unique - no duplicates. This operator acts like the logical or operator.

entities = msp.query()
# select all entities with color < 2 or color > 7
result = (entities.color < 2 ) | (entities.color > 7)

The & operator or EntityQuery.intersection() returns a new EntityQuery with entities common to self and other. This operator acts like the logical and operator.

entities = msp.query()
# select all entities with color > 1 and color < 7
result = (entities.color > 1) & (entities.color < 7)

The - operator or EntityQuery.difference() returns a new EntityQuery with all entities from self that are not in other.

entities = msp.query()
# select all entities with color > 1 and not layer == "MyLayer"
result = (entities.color > 1) - (entities.layer != "MyLayer")

The ^ operator or EntityQuery.symmetric_difference() returns a new EntityQuery with entities in either self or other but not both.

entities = msp.query()
# select all entities with color > 1 or layer == "MyLayer", exclusive
# entities with color > 1 and layer == "MyLayer"
result = (entities.color > 1) ^ (entities.layer == "MyLayer")

The new() Function

ezdxf.query.new(entities: Iterable[DXFEntity] | None = None, query: str = '*') EntityQuery

Start a new query based on sequence entities. The entities argument has to be an iterable of DXFEntity or inherited objects and returns an EntityQuery object.