Skip to content

project

Classes:

Name Description
Bookmark
BookmarkManager
BookmarkMapSeries

Wrapper around an arcpy.mp BookmarkMapSeries object that provides an ergonomic interface

ElevationSurface
ElevationSurfaceManager
Layer

mp.Layer wrapper

LayerManager
Layout
LayoutManager
Manager

Base access interfaces for all manager classes. Specific interfaces are defined in the subclass

Map
MapManager
MapSeries

Wrapper around an arcpy.mp MapSeries object that provides an ergonomic interface

MappingWrapper

Internal wrapper class for wrapping existing objects with new functionality

Project

Wrapper for an ArcGISProject (.aprx)

Report
ReportManager
Table
TableManager
Wildcard

Clarify that the string passed to a Manager index is a wildcard so the type checker knows you're getting a Sequence back

Functions:

Name Description
name_of

Handle the naming hierarchy of mapping objects URI -> longName -> name

Bookmark

Bases: MappingWrapper[Bookmark, CIMBookmark], Bookmark

Source code in src/arcpie/project.py
227
class Bookmark(MappingWrapper[_Bookmark, CIMBookmark], _Bookmark): ...

BookmarkManager

Bases: Manager[Bookmark]

Source code in src/arcpie/project.py
698
class BookmarkManager(Manager[Bookmark]): ...

BookmarkMapSeries

Bases: MappingWrapper[BookmarkMapSeries, CIMBookmarkMapSeries], BookmarkMapSeries

Wrapper around an arcpy.mp BookmarkMapSeries object that provides an ergonomic interface

Methods:

Name Description
__getitem__

Allow indexing the BookmarkMapSeries by name, index, or Bookmark object

__iter__
__len__
Source code in src/arcpie/project.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
class BookmarkMapSeries(MappingWrapper[_BookmarkMapSeries, CIMBookmarkMapSeries], _BookmarkMapSeries):
    """Wrapper around an arcpy.mp BookmarkMapSeries object that provides an ergonomic interface"""

    def __iter__(self) -> Iterator[BookmarkMapSeries]:
        _orig_page = self.currentPageNumber
        for page in range(1, self.pageCount):
            self.currentPageNumber = page
            yield self
        if _orig_page:
            self.currentPageNumber = _orig_page

    def __getitem__(self, page: int|str|_Bookmark) -> BookmarkMapSeries:
        """Allow indexing the BookmarkMapSeries by name, index, or Bookmark object"""
        match page:
            case _Bookmark():
                self.currentBookmark = page
            case str():
                self.currentPageNumber = self.getPageNumberFromName(page)
            case int():
                self.currentPageNumber = page
        return self

    def __len__(self) -> int:
        return len(self.bookmarks)

__getitem__(page)

Allow indexing the BookmarkMapSeries by name, index, or Bookmark object

Source code in src/arcpie/project.py
240
241
242
243
244
245
246
247
248
249
def __getitem__(self, page: int|str|_Bookmark) -> BookmarkMapSeries:
    """Allow indexing the BookmarkMapSeries by name, index, or Bookmark object"""
    match page:
        case _Bookmark():
            self.currentBookmark = page
        case str():
            self.currentPageNumber = self.getPageNumberFromName(page)
        case int():
            self.currentPageNumber = page
    return self

__iter__()

Source code in src/arcpie/project.py
232
233
234
235
236
237
238
def __iter__(self) -> Iterator[BookmarkMapSeries]:
    _orig_page = self.currentPageNumber
    for page in range(1, self.pageCount):
        self.currentPageNumber = page
        yield self
    if _orig_page:
        self.currentPageNumber = _orig_page

__len__()

Source code in src/arcpie/project.py
251
252
def __len__(self) -> int:
    return len(self.bookmarks)

ElevationSurface

Bases: MappingWrapper[ElevationSurface, CIMElevationSurfaceLayer], ElevationSurface

Source code in src/arcpie/project.py
353
class ElevationSurface(MappingWrapper[_ElevationSurface, CIMElevationSurfaceLayer], _ElevationSurface): ...

ElevationSurfaceManager

Bases: Manager[ElevationSurface]

Source code in src/arcpie/project.py
699
class ElevationSurfaceManager(Manager[ElevationSurface]): ...

Layer

Bases: MappingWrapper[Layer, CIMBaseLayer], Layer

mp.Layer wrapper

Methods:

Name Description
export_lyrx

Export the layer to a lyrx file in the target directory

import_lyrx

Import the layer state from an lyrx file

Attributes:

Name Type Description
cim CIMBaseLayer
feature_class FeatureClass

Get a arcpie.FeatureClass object that is initialized using the layer and its current state

lyrx dict[str, Any] | None

Get a dictionary representation of the layer that can be saved to an lyrx file using json.dumps

symbology Symbology

Get the base symbology object for the layer

Source code in src/arcpie/project.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
class Layer(MappingWrapper[_Layer, CIMBaseLayer], _Layer):
    """mp.Layer wrapper"""

    @property
    def feature_class(self) -> FeatureClass:
        """Get a `arcpie.FeatureClass` object that is initialized using the layer and its current state"""
        return FeatureClass.from_layer(self)

    @property
    def symbology(self) -> Symbology:
        """Get the base symbology object for the layer"""
        return self._obj.symbology

    @property
    def lyrx(self) -> dict[str, Any] | None:
        """Get a dictionary representation of the layer that can be saved to an lyrx file using `json.dumps`

        Note:
            GroupLayer objects will return a lyrx template with all sub-layers included
        """
        _def = self.cim_dict
        if _def is None:
            return None
        _lyrx: dict[str, Any] = { # Base required keys for lyrx file
            'type': 'CIMLayerDocument',
            'layers': [self.uri],
            'layerDefinitions': [_def],
        }

        # Handle Group Layers
        if self.isGroupLayer and self.parent and isinstance(self.parent, Map):
            if _child_tables := [uri for uri in _def.get('tables', [])]:
                _child_tables: list[str]
                _table_uris = set(_child_tables) & set(self.parent.tables.uris) # Skip dead nodes
                _lyrx['tableDefinitions'] = [self.parent.tables[uri].cim_dict for uri in _table_uris]
            if _child_layers := [uri for uri in _def.get('layers', [])]:
                _child_layers: list[str]
                _layer_uris = set(_child_layers) & set(self.parent.layers.uris) # Skip dead nodes
                _lyrx['layerDefinitions'] = [_def] + [self.parent.layers[uri].cim_dict for uri in _layer_uris]
        return _lyrx

    @property
    def cim(self) -> CIMBaseLayer:
        return super().cim

    def export_lyrx(self, out_dir: Path|str) -> None:
        """Export the layer to a lyrx file in the target directory

        Args:
            out_dir (Path|str): The location to export the mapx to
        """
        out_dir = Path(out_dir)
        target = out_dir / f'{self.longName}.lyrx'
        # Make Containing directory for grouped layers
        target.parent.mkdir(exist_ok=True, parents=True)
        target.write_text(json.dumps(self.lyrx, indent=2), encoding='utf-8')

    def import_lyrx(self, lyrx: Path|str) -> None:
        """Import the layer state from an lyrx file

        Args:
            lyrx (Path|str): The lyrx file to update this layer with

        Note:
            CIM changes require the APRX to be saved to take effect. If you are accessing this
            layer via a Project, use `project.save()` after importing the layerfile
        """
        _lyrx = LayerFile(str(lyrx))
        _lyrx_layers = {l.name: l for l in _lyrx.listLayers()}
        if not (_lyrx_layer := _lyrx_layers.get(self.name)):
            print(f'{self.name} not found in {str(lyrx)}')
        else:
            # Update Connection
            _lyrx_layer = Layer(_lyrx_layer)
            _lyrx_cim_dict = _lyrx_layer.cim_dict or {}
            _lyrx_layer_cim = _lyrx_layer.cim
            if _lyrx_cim_dict.get('featureTable') and _lyrx_cim_dict['featureTable'].get('dataConnection'):
                _lyrx_layer_cim.featureTable.dataConnection = self.cim.featureTable.dataConnection # type: ignore (this is how CIM works)
            try:
                self.setDefinition(_lyrx_layer_cim) # pyright: ignore[reportArgumentType]
            except AttributeError:
                print(f'Failed to update CIM for {self.__class__.__name__}{self.name}')

cim property

feature_class property

Get a arcpie.FeatureClass object that is initialized using the layer and its current state

lyrx property

Get a dictionary representation of the layer that can be saved to an lyrx file using json.dumps

Note

GroupLayer objects will return a lyrx template with all sub-layers included

symbology property

Get the base symbology object for the layer

export_lyrx(out_dir)

Export the layer to a lyrx file in the target directory

Parameters:

Name Type Description Default
out_dir Path | str

The location to export the mapx to

required
Source code in src/arcpie/project.py
189
190
191
192
193
194
195
196
197
198
199
def export_lyrx(self, out_dir: Path|str) -> None:
    """Export the layer to a lyrx file in the target directory

    Args:
        out_dir (Path|str): The location to export the mapx to
    """
    out_dir = Path(out_dir)
    target = out_dir / f'{self.longName}.lyrx'
    # Make Containing directory for grouped layers
    target.parent.mkdir(exist_ok=True, parents=True)
    target.write_text(json.dumps(self.lyrx, indent=2), encoding='utf-8')

import_lyrx(lyrx)

Import the layer state from an lyrx file

Parameters:

Name Type Description Default
lyrx Path | str

The lyrx file to update this layer with

required
Note

CIM changes require the APRX to be saved to take effect. If you are accessing this layer via a Project, use project.save() after importing the layerfile

Source code in src/arcpie/project.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
def import_lyrx(self, lyrx: Path|str) -> None:
    """Import the layer state from an lyrx file

    Args:
        lyrx (Path|str): The lyrx file to update this layer with

    Note:
        CIM changes require the APRX to be saved to take effect. If you are accessing this
        layer via a Project, use `project.save()` after importing the layerfile
    """
    _lyrx = LayerFile(str(lyrx))
    _lyrx_layers = {l.name: l for l in _lyrx.listLayers()}
    if not (_lyrx_layer := _lyrx_layers.get(self.name)):
        print(f'{self.name} not found in {str(lyrx)}')
    else:
        # Update Connection
        _lyrx_layer = Layer(_lyrx_layer)
        _lyrx_cim_dict = _lyrx_layer.cim_dict or {}
        _lyrx_layer_cim = _lyrx_layer.cim
        if _lyrx_cim_dict.get('featureTable') and _lyrx_cim_dict['featureTable'].get('dataConnection'):
            _lyrx_layer_cim.featureTable.dataConnection = self.cim.featureTable.dataConnection # type: ignore (this is how CIM works)
        try:
            self.setDefinition(_lyrx_layer_cim) # pyright: ignore[reportArgumentType]
        except AttributeError:
            print(f'Failed to update CIM for {self.__class__.__name__}{self.name}')

LayerManager

Bases: Manager[Layer]

Source code in src/arcpie/project.py
695
class LayerManager(Manager[Layer]): ...

Layout

Bases: MappingWrapper[Layout, CIMLayout], Layout

Methods:

Name Description
to_pdf

Get the bytes for a pdf export of the Layout

Attributes:

Name Type Description
mapseries MapSeries | BookmarkMapSeries | None

Get the Layout MapSeries/BookmarkMapSeries if it exists

pagx dict[str, Any]

Access the raw CIM dictionary of the layout

Source code in src/arcpie/project.py
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
class Layout(MappingWrapper[_Layout, CIMLayout], _Layout):

    @property
    def mapseries(self) -> MapSeries | BookmarkMapSeries| None:
        """Get the Layout MapSeries/BookmarkMapSeries if it exists"""
        if not self.mapSeries:
            return None
        if isinstance(self.mapSeries, _MapSeries):
            return MapSeries(self.mapSeries, self)
        return BookmarkMapSeries(self.mapSeries, self)

    @property
    def pagx(self) -> dict[str, Any]:
        """Access the raw CIM dictionary of the layout

        Returns:
            (dict[str, Any]): A dictionary representation of the pagx json
        """
        with NamedTemporaryFile() as tmp:
            self.exportToPAGX(tmp.name)
            return json.loads(Path(f'{tmp.name}.pagx').read_text(encoding='utf-8'))

    def to_pdf(self, **settings: Unpack[PDFSetting]) -> BytesIO:
        """Get the bytes for a pdf export of the Layout

        Args:
            **settings (PDFSetting): Optional settings for the export (default: `PDFDefault`)

        Returns:
            (bytes): Raw bytes of the PDF for use in a write operation or stream

        Example:
            ```python
                # Get the layout object from a project file
                lyt = prj.layouts['Layout_1']

                # Create a pdf then write the output of to_pdf to it
                pdf = Path('pdf_path').write_bytes(lyt.to_pdf())
            ```   
        """
        with NamedTemporaryFile() as tmp:
            _settings = PDFDefault.copy()
            for arg in _settings:
                if val := settings.get(arg):
                    _settings[arg] = val
            pdf = self.exportToPDF(tmp.name, **_settings)
            return BytesIO(Path(pdf).open('rb').read())

mapseries property

Get the Layout MapSeries/BookmarkMapSeries if it exists

pagx property

Access the raw CIM dictionary of the layout

Returns:

Type Description
dict[str, Any]

A dictionary representation of the pagx json

to_pdf(**settings)

Get the bytes for a pdf export of the Layout

Parameters:

Name Type Description Default
**settings PDFSetting

Optional settings for the export (default: PDFDefault)

{}

Returns:

Type Description
bytes

Raw bytes of the PDF for use in a write operation or stream

Example
    # Get the layout object from a project file
    lyt = prj.layouts['Layout_1']

    # Create a pdf then write the output of to_pdf to it
    pdf = Path('pdf_path').write_bytes(lyt.to_pdf())
Source code in src/arcpie/project.py
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
def to_pdf(self, **settings: Unpack[PDFSetting]) -> BytesIO:
    """Get the bytes for a pdf export of the Layout

    Args:
        **settings (PDFSetting): Optional settings for the export (default: `PDFDefault`)

    Returns:
        (bytes): Raw bytes of the PDF for use in a write operation or stream

    Example:
        ```python
            # Get the layout object from a project file
            lyt = prj.layouts['Layout_1']

            # Create a pdf then write the output of to_pdf to it
            pdf = Path('pdf_path').write_bytes(lyt.to_pdf())
        ```   
    """
    with NamedTemporaryFile() as tmp:
        _settings = PDFDefault.copy()
        for arg in _settings:
            if val := settings.get(arg):
                _settings[arg] = val
        pdf = self.exportToPDF(tmp.name, **_settings)
        return BytesIO(Path(pdf).open('rb').read())

LayoutManager

Bases: Manager[Layout]

Source code in src/arcpie/project.py
696
class LayoutManager(Manager[Layout]): ...

Manager

Bases: Generic[_MappingObject]

Base access interfaces for all manager classes. Specific interfaces are defined in the subclass

Index itentifiers are URI -> longName -> name depending on what is available in the managed class

Methods:

Name Description
__contains__

Check to see if a URI/name is present in the Manager

__getitem__

Access objects using a regex pattern (re.compile), wildcard (STRING), index, slice, name, or URI

__init__
__iter__
__len__
get

Get a value from the Project with a safe default value

Attributes:

Name Type Description
names list[str]

Get the names of all managed objects (skips URIs)

objects list[_MappingObject]

Get a list of all managed objects

uris list[str]

Get URIs/CIMPATH for all managed objects

Source code in src/arcpie/project.py
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
class Manager(Generic[_MappingObject]):
    """Base access interfaces for all manager classes. Specific interfaces are defined in the subclass

    Index itentifiers are URI -> longName -> name depending on what is available in the managed class
    """

    def __init__(self, objs: Iterable[_MappingObject]) -> None:
        self._objects: dict[str, _MappingObject] = {}
        for o in objs:
            if (_uri := o.uri) not in self._objects:
                self._objects[_uri] = o

    @property
    def objects(self) -> list[_MappingObject]:
        """Get a list of all managed objects"""
        return list(self._objects.values())

    @property
    def names(self) -> list[str]:
        """Get the names of all managed objects (skips URIs)"""
        return [o.unique_name for o in self.objects]

    @property
    def uris(self) -> list[str]:
        """Get URIs/CIMPATH for all managed objects

        Note:
            Default to a Python id() call if no URI is present
        """
        return [o.uri for o in self.objects]

    @overload
    def __getitem__(self, name: str) -> _MappingObject: ...
    @overload
    def __getitem__(self, name: int) -> _MappingObject: ...
    @overload
    def __getitem__(self, name: Wildcard) -> list[_MappingObject]: ...
    @overload
    def __getitem__(self, name: re.Pattern[str]) -> list[_MappingObject]: ...
    @overload
    def __getitem__(self, name: slice) -> list[_MappingObject]: ...

    def __getitem__(self, name: str|Wildcard|re.Pattern[str]|int|slice) -> _MappingObject|list[_MappingObject]:
        """Access objects using a regex pattern (re.compile), wildcard (*STRING*), index, slice, name, or URI"""
        if isinstance(name, str) and '*' in name:
            name = Wildcard(name) # Allow passing a wildcard directly (lose type inference)
        match name:
            case int() | slice():
                return self.objects[name] # Will raise IndexError
            case str(name) if name in self._objects:
                return self._objects[name]
            case str(name) if name in self.names:
                for o in self.objects:
                    if o.unique_name == name:
                        return o
            case re.Pattern():
                return [o for o in self.objects if name.match(name_of(o, skip_uri=True))]
            case Wildcard():
                return [o for o in self.objects if all(part in name_of(o, skip_uri=True) for part in name.split('*'))]
            case _ :
                pass # Fallthrough to raise a KeyError

        raise KeyError(f'{name} not found in objects: ({self.names})')

    @overload
    def get(self, name: str) -> _MappingObject: ...
    @overload
    def get(self, name: Wildcard) -> list[_MappingObject]: ...
    @overload
    def get(self, name: str, default: _Default) -> _MappingObject | _Default: ...
    @overload
    def get(self, name: Wildcard, default: _Default) -> list[_MappingObject] | _Default: ...
    def get(self, name: str|Wildcard, default: _Default|None=None) -> _MappingObject|list[_MappingObject]|_Default|None:
        """Get a value from the Project with a safe default value"""
        try:
            return self[name]
        except KeyError:
            return default

    def __contains__(self, name: str|_MappingObject) -> bool:
        """Check to see if a URI/name is present in the Manager"""
        match name:
            case str():
                return True if self.get(name) else False
            case _:
                return any(o == name for o in self.objects)

    def __iter__(self) -> Iterator[_MappingObject]:
        return iter(self._objects.values())

    def __len__(self) -> int:
        return len(self._objects)

names property

Get the names of all managed objects (skips URIs)

objects property

Get a list of all managed objects

uris property

Get URIs/CIMPATH for all managed objects

Note

Default to a Python id() call if no URI is present

__contains__(name)

Check to see if a URI/name is present in the Manager

Source code in src/arcpie/project.py
678
679
680
681
682
683
684
def __contains__(self, name: str|_MappingObject) -> bool:
    """Check to see if a URI/name is present in the Manager"""
    match name:
        case str():
            return True if self.get(name) else False
        case _:
            return any(o == name for o in self.objects)

__getitem__(name)

__getitem__(name: str) -> _MappingObject
__getitem__(name: int) -> _MappingObject
__getitem__(name: Wildcard) -> list[_MappingObject]
__getitem__(name: re.Pattern[str]) -> list[_MappingObject]
__getitem__(name: slice) -> list[_MappingObject]

Access objects using a regex pattern (re.compile), wildcard (STRING), index, slice, name, or URI

Source code in src/arcpie/project.py
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
def __getitem__(self, name: str|Wildcard|re.Pattern[str]|int|slice) -> _MappingObject|list[_MappingObject]:
    """Access objects using a regex pattern (re.compile), wildcard (*STRING*), index, slice, name, or URI"""
    if isinstance(name, str) and '*' in name:
        name = Wildcard(name) # Allow passing a wildcard directly (lose type inference)
    match name:
        case int() | slice():
            return self.objects[name] # Will raise IndexError
        case str(name) if name in self._objects:
            return self._objects[name]
        case str(name) if name in self.names:
            for o in self.objects:
                if o.unique_name == name:
                    return o
        case re.Pattern():
            return [o for o in self.objects if name.match(name_of(o, skip_uri=True))]
        case Wildcard():
            return [o for o in self.objects if all(part in name_of(o, skip_uri=True) for part in name.split('*'))]
        case _ :
            pass # Fallthrough to raise a KeyError

    raise KeyError(f'{name} not found in objects: ({self.names})')

__init__(objs)

Source code in src/arcpie/project.py
605
606
607
608
609
def __init__(self, objs: Iterable[_MappingObject]) -> None:
    self._objects: dict[str, _MappingObject] = {}
    for o in objs:
        if (_uri := o.uri) not in self._objects:
            self._objects[_uri] = o

__iter__()

Source code in src/arcpie/project.py
686
687
def __iter__(self) -> Iterator[_MappingObject]:
    return iter(self._objects.values())

__len__()

Source code in src/arcpie/project.py
689
690
def __len__(self) -> int:
    return len(self._objects)

get(name, default=None)

get(name: str) -> _MappingObject
get(name: Wildcard) -> list[_MappingObject]
get(
    name: str, default: _Default
) -> _MappingObject | _Default
get(
    name: Wildcard, default: _Default
) -> list[_MappingObject] | _Default

Get a value from the Project with a safe default value

Source code in src/arcpie/project.py
671
672
673
674
675
676
def get(self, name: str|Wildcard, default: _Default|None=None) -> _MappingObject|list[_MappingObject]|_Default|None:
    """Get a value from the Project with a safe default value"""
    try:
        return self[name]
    except KeyError:
        return default

Map

Bases: MappingWrapper[Map, CIMMapDocument], Map

Methods:

Name Description
__getitem__
export_assoc_lyrx

Export all child layers to lyrx files the target directory

export_mapx

Export the map definitions to a mapx file in the target directory

get
import_assoc_lyrx

Imports lyrx files that were exported using the export_assoc_lyrx method

import_mapx

Attributes:

Name Type Description
bookmarks BookmarkManager

Get a BookmarkManager for all bookmarks in the Map

cim CIMMapDocument
cim_dict dict[str, Any]
elevation_surfaces ElevationSurfaceManager

Get an ElevationSurfaceManager for all elevation surfaces in the Map

layers LayerManager

Get a LayerManager for all layers in the Map

mapx dict[str, Any]
tables TableManager

Get a TableManager for all tables in the Map

Source code in src/arcpie/project.py
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
class Map(MappingWrapper[_Map, CIMMapDocument], _Map):
    @cached_property
    def layers(self) -> LayerManager:
        """Get a LayerManager for all layers in the Map"""
        return LayerManager(Layer(l, self) for l in self.listLayers() or [])

    @cached_property
    def tables(self) -> TableManager:
        """Get a TableManager for all tables in the Map"""
        return TableManager(Table(t, self) for t in self.listTables() or [])

    @cached_property
    def bookmarks(self) -> BookmarkManager:
        """Get a BookmarkManager for all bookmarks in the Map"""
        return BookmarkManager(Bookmark(b, self) for b in self.listBookmarks() or [])

    @cached_property
    def elevation_surfaces(self) -> ElevationSurfaceManager:
        """Get an ElevationSurfaceManager for all elevation surfaces in the Map"""
        return ElevationSurfaceManager(ElevationSurface(es, self) for es in self.listElevationSurfaces() or [])

    @property
    def mapx(self) -> dict[str, Any]:
        with NamedTemporaryFile(suffix='.mapx') as tmp:
            self.exportToMAPX(tmp.name)
            return json.loads(Path(tmp.name).read_text(encoding='utf-8'))

    @property
    def cim(self) -> CIMMapDocument:
        return super().cim

    @property
    def cim_dict(self) -> dict[str, Any]:
        return json.loads(json.dumps(self.cim, cls=CimJsonEncoder, indent=2))

    @overload
    def __getitem__(self, name: str) -> Layer | Table: ...
    @overload
    def __getitem__(self, name: Wildcard) -> list[Layer] | list[Table]: ...
    def __getitem__(self, name: str | Wildcard) -> Any:
        _obj = self.layers.get(name, None) or self.tables.get(name, None)
        if _obj is None:
            raise KeyError(f'{name} not found in map {self.unique_name}')
        return _obj

    @overload
    def get(self, name: str, default: _Default) -> Layer | Table | _Default: ...
    @overload
    def get(self, name: Wildcard, default: _Default) -> list[Layer] | list[Table] | _Default: ...
    def get(self, name: str | Wildcard, default: _Default=None) -> Any | _Default:
        try:
            return self[name]
        except KeyError:
            return default

    def export_mapx(self, out_dir: Path|str) -> None:
        """Export the map definitions to a mapx file in the target directory

        Args:
            out_dir (Path|str): The location to export the mapx to
        """
        target = Path(out_dir) / f'{self.unique_name}'
        target.write_text(json.dumps(self.mapx, indent=2), encoding='utf-8')

    def export_assoc_lyrx(self, out_dir: Path|str, *, skip_groups: bool=False, skip_grouped: bool=False) -> None:
        """Export all child layers to lyrx files the target directory

        Args:
            out_dir (Path|str): The location to export the lyrx files to
            skip_groups (bool): Skip group layerfiles and export each layer individually in a group subdirectory (default: False)
            skip_grouped (bool): Inverse of skip groups and instead only exports the group lyrx, skipping the individual layers (default: False)
        """
        out_dir = Path(out_dir)
        for layer in self.layers:
            if layer.isGroupLayer and skip_groups:
                continue
            try:
                layer.export_lyrx(out_dir / self.unique_name)
            except json.JSONDecodeError as e:
                print(f'Failed to export layer: {layer}: {e}')

        for table in self.tables:
            try:
                table.export_lyrx(out_dir / self.unique_name)
            except json.JSONDecodeError as e:
                print(f'Failed to export table: {table}: {e}')

    def import_assoc_lyrx(self, lyrx_dir: Path|str, *, skip_groups: bool=False) -> None:
        """Imports lyrx files that were exported using the `export_assoc_lyrx` method

        Args:
            lyrx_dir (Path|str): The directory containing the previously exported lyrx files

        Note:
            CIM changes require the APRX to be saved to take effect. If you are accessing this
            layer via a Project, use `project.save()` after importing the layerfile
        """
        lyrx_dir = Path(lyrx_dir)
        for lyrx_path in lyrx_dir.rglob('*.lyrx'):
            _lyrx_name = str(lyrx_path.relative_to(lyrx_dir).with_suffix(''))
            if _lyrx_name in self.layers:
                if self.layers[_lyrx_name].isGroupLayer and skip_groups:
                    continue
                self.layers[_lyrx_name].import_lyrx(lyrx_path)
            elif _lyrx_name in self.tables:
                self.tables[_lyrx_name].import_lyrx(lyrx_path)

    def import_mapx(self, mapx: Path|str) -> None:
        raise NotImplementedError()

bookmarks cached property

Get a BookmarkManager for all bookmarks in the Map

cim property

cim_dict property

elevation_surfaces cached property

Get an ElevationSurfaceManager for all elevation surfaces in the Map

layers cached property

Get a LayerManager for all layers in the Map

mapx property

tables cached property

Get a TableManager for all tables in the Map

__getitem__(name)

__getitem__(name: str) -> Layer | Table
__getitem__(name: Wildcard) -> list[Layer] | list[Table]
Source code in src/arcpie/project.py
394
395
396
397
398
def __getitem__(self, name: str | Wildcard) -> Any:
    _obj = self.layers.get(name, None) or self.tables.get(name, None)
    if _obj is None:
        raise KeyError(f'{name} not found in map {self.unique_name}')
    return _obj

export_assoc_lyrx(out_dir, *, skip_groups=False, skip_grouped=False)

Export all child layers to lyrx files the target directory

Parameters:

Name Type Description Default
out_dir Path | str

The location to export the lyrx files to

required
skip_groups bool

Skip group layerfiles and export each layer individually in a group subdirectory (default: False)

False
skip_grouped bool

Inverse of skip groups and instead only exports the group lyrx, skipping the individual layers (default: False)

False
Source code in src/arcpie/project.py
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
def export_assoc_lyrx(self, out_dir: Path|str, *, skip_groups: bool=False, skip_grouped: bool=False) -> None:
    """Export all child layers to lyrx files the target directory

    Args:
        out_dir (Path|str): The location to export the lyrx files to
        skip_groups (bool): Skip group layerfiles and export each layer individually in a group subdirectory (default: False)
        skip_grouped (bool): Inverse of skip groups and instead only exports the group lyrx, skipping the individual layers (default: False)
    """
    out_dir = Path(out_dir)
    for layer in self.layers:
        if layer.isGroupLayer and skip_groups:
            continue
        try:
            layer.export_lyrx(out_dir / self.unique_name)
        except json.JSONDecodeError as e:
            print(f'Failed to export layer: {layer}: {e}')

    for table in self.tables:
        try:
            table.export_lyrx(out_dir / self.unique_name)
        except json.JSONDecodeError as e:
            print(f'Failed to export table: {table}: {e}')

export_mapx(out_dir)

Export the map definitions to a mapx file in the target directory

Parameters:

Name Type Description Default
out_dir Path | str

The location to export the mapx to

required
Source code in src/arcpie/project.py
410
411
412
413
414
415
416
417
def export_mapx(self, out_dir: Path|str) -> None:
    """Export the map definitions to a mapx file in the target directory

    Args:
        out_dir (Path|str): The location to export the mapx to
    """
    target = Path(out_dir) / f'{self.unique_name}'
    target.write_text(json.dumps(self.mapx, indent=2), encoding='utf-8')

get(name, default=None)

get(
    name: str, default: _Default
) -> Layer | Table | _Default
get(
    name: Wildcard, default: _Default
) -> list[Layer] | list[Table] | _Default
Source code in src/arcpie/project.py
404
405
406
407
408
def get(self, name: str | Wildcard, default: _Default=None) -> Any | _Default:
    try:
        return self[name]
    except KeyError:
        return default

import_assoc_lyrx(lyrx_dir, *, skip_groups=False)

Imports lyrx files that were exported using the export_assoc_lyrx method

Parameters:

Name Type Description Default
lyrx_dir Path | str

The directory containing the previously exported lyrx files

required
Note

CIM changes require the APRX to be saved to take effect. If you are accessing this layer via a Project, use project.save() after importing the layerfile

Source code in src/arcpie/project.py
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
def import_assoc_lyrx(self, lyrx_dir: Path|str, *, skip_groups: bool=False) -> None:
    """Imports lyrx files that were exported using the `export_assoc_lyrx` method

    Args:
        lyrx_dir (Path|str): The directory containing the previously exported lyrx files

    Note:
        CIM changes require the APRX to be saved to take effect. If you are accessing this
        layer via a Project, use `project.save()` after importing the layerfile
    """
    lyrx_dir = Path(lyrx_dir)
    for lyrx_path in lyrx_dir.rglob('*.lyrx'):
        _lyrx_name = str(lyrx_path.relative_to(lyrx_dir).with_suffix(''))
        if _lyrx_name in self.layers:
            if self.layers[_lyrx_name].isGroupLayer and skip_groups:
                continue
            self.layers[_lyrx_name].import_lyrx(lyrx_path)
        elif _lyrx_name in self.tables:
            self.tables[_lyrx_name].import_lyrx(lyrx_path)

import_mapx(mapx)

Source code in src/arcpie/project.py
462
463
def import_mapx(self, mapx: Path|str) -> None:
    raise NotImplementedError()

MapManager

Bases: Manager[Map]

Source code in src/arcpie/project.py
694
class MapManager(Manager[Map]): ...

MapSeries

Bases: MappingWrapper[MapSeries, CIMMapSeries], MapSeries

Wrapper around an arcpy.mp MapSeries object that provides an ergonomic interface

Methods:

Name Description
__getitem__

Allow indexing a mapseries by a page name or a page index/number

__iter__
__len__
__repr__
to_pdf

Export the MapSeries to a PDF, See Layer.to_pdf for more info

Attributes:

Name Type Description
current_page_name str

Get the name of the active mapseries page

feature_class FeatureClass

Get the FeatureClass of the parent layer

layer Layer

Get the mapseries target layer

map Map

Get the map object that is being seriesed

pageRow

Get a Row object for the active mapseries page

page_field str

Get fieldname used as pagename

page_field_names list[str]

Get all fieldnames for the mapseriesed features

page_values dict[str, Any]

Get a mapping of values for the current page

valid_pages list[str]

Get all valid page names for the MapSeries

Source code in src/arcpie/project.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
class MapSeries(MappingWrapper[_MapSeries, CIMMapSeries], _MapSeries):
    """Wrapper around an arcpy.mp MapSeries object that provides an ergonomic interface"""
    @property
    def layer(self) -> Layer:
        """Get the mapseries target layer"""
        return Layer(self.indexLayer, self.map)

    @property # Passthrough
    def feature_class(self) -> FeatureClass:
        """Get the FeatureClass of the parent layer"""
        return self.layer.feature_class

    @property
    def map(self) -> Map:
        """Get the map object that is being seriesed"""
        return Map(self.mapFrame.map, self.parent.parent) #type: ignore (if a MapSeries is initialized this will be a map)

    @property
    def pageRow(self): # type: ignore (prevent access to uninitialized pageRow raising RuntimeError)
        """Get a Row object for the active mapseries page"""
        try:
            return self._obj.pageRow
        except RuntimeError:
            return None

    @property
    def page_field(self) -> str:
        """Get fieldname used as pagename"""
        return self.pageNameField.name

    @cached_property
    def page_field_names(self) -> list[str]:
        """Get all fieldnames for the mapseriesed features"""
        return [f for f in self.feature_class.fields if not f.startswith('@')]

    @property
    def valid_pages(self) -> list[str]:
        """Get all valid page names for the MapSeries"""
        return list(self.feature_class[self.page_field])

    @property
    def page_values(self) -> dict[str, Any]:
        """Get a mapping of values for the current page"""
        if not self.pageRow:
            return {} # pageRow is unset with no active page

        # Need to access a private `_asdict` method of Row because getValue is broken
        return {f: self.pageRow._asdict().get(f) for f in self.page_field_names}

    @property
    def current_page_name(self) -> str:
        """Get the name of the active mapseries page"""
        return self.page_values.get(self.page_field, 'No Page')

    def to_pdf(self, **settings: Unpack[MapSeriesPDFSetting]) -> BytesIO:
        """Export the MapSeries to a PDF, See Layer.to_pdf for more info

        Args:
            **settings (Unpack[MapSeriesPDFSetting]): Passthrough kwargs for layout.exportToPDF

        Note:
            By default, printing a mapseries will print all pages to a single file. To only print
            the active page:
            ```python
            >>> ms.to_pdf(page_range_type='CURRENT')
            ```
        """
        _settings = MapseriesPDFDefault.copy()
        _settings.update(settings)
        with NamedTemporaryFile() as tmp:
            return BytesIO(Path(self.exportToPDF(tmp.name, **_settings)).open('rb').read())

    def __iter__(self) -> Iterator[MapSeries]:
        _orig_page = self.currentPageNumber
        for page in range(1, self.pageCount+1):
            self.currentPageNumber = page
            yield self
        if _orig_page:
            self.currentPageNumber = _orig_page

    def __getitem__(self, page: int|str) -> MapSeries:
        """Allow indexing a mapseries by a page name or a page index/number"""
        match page:
            case str():
                if page not in self.valid_pages:
                    raise KeyError(f"{page} is not a valid page name!")
                self.currentPageNumber = self.getPageNumberFromName(page)
            case int():
                if page not in range(1, self.pageCount):
                    raise IndexError(f"{self} only has {self.pageCount} pages, {page} out of range")
                self.currentPageNumber = page
        return self

    def __len__(self) -> int:
        return self.pageCount

    def __repr__(self) -> str:
        return f'MapSeries<{self.layer.unique_name} @ {self.current_page_name}>'

current_page_name property

Get the name of the active mapseries page

feature_class property

Get the FeatureClass of the parent layer

layer property

Get the mapseries target layer

map property

Get the map object that is being seriesed

pageRow property

Get a Row object for the active mapseries page

page_field property

Get fieldname used as pagename

page_field_names cached property

Get all fieldnames for the mapseriesed features

page_values property

Get a mapping of values for the current page

valid_pages property

Get all valid page names for the MapSeries

__getitem__(page)

Allow indexing a mapseries by a page name or a page index/number

Source code in src/arcpie/project.py
334
335
336
337
338
339
340
341
342
343
344
345
def __getitem__(self, page: int|str) -> MapSeries:
    """Allow indexing a mapseries by a page name or a page index/number"""
    match page:
        case str():
            if page not in self.valid_pages:
                raise KeyError(f"{page} is not a valid page name!")
            self.currentPageNumber = self.getPageNumberFromName(page)
        case int():
            if page not in range(1, self.pageCount):
                raise IndexError(f"{self} only has {self.pageCount} pages, {page} out of range")
            self.currentPageNumber = page
    return self

__iter__()

Source code in src/arcpie/project.py
326
327
328
329
330
331
332
def __iter__(self) -> Iterator[MapSeries]:
    _orig_page = self.currentPageNumber
    for page in range(1, self.pageCount+1):
        self.currentPageNumber = page
        yield self
    if _orig_page:
        self.currentPageNumber = _orig_page

__len__()

Source code in src/arcpie/project.py
347
348
def __len__(self) -> int:
    return self.pageCount

__repr__()

Source code in src/arcpie/project.py
350
351
def __repr__(self) -> str:
    return f'MapSeries<{self.layer.unique_name} @ {self.current_page_name}>'

to_pdf(**settings)

Export the MapSeries to a PDF, See Layer.to_pdf for more info

Parameters:

Name Type Description Default
**settings Unpack[MapSeriesPDFSetting]

Passthrough kwargs for layout.exportToPDF

{}
Note

By default, printing a mapseries will print all pages to a single file. To only print the active page:

>>> ms.to_pdf(page_range_type='CURRENT')

Source code in src/arcpie/project.py
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
def to_pdf(self, **settings: Unpack[MapSeriesPDFSetting]) -> BytesIO:
    """Export the MapSeries to a PDF, See Layer.to_pdf for more info

    Args:
        **settings (Unpack[MapSeriesPDFSetting]): Passthrough kwargs for layout.exportToPDF

    Note:
        By default, printing a mapseries will print all pages to a single file. To only print
        the active page:
        ```python
        >>> ms.to_pdf(page_range_type='CURRENT')
        ```
    """
    _settings = MapseriesPDFDefault.copy()
    _settings.update(settings)
    with NamedTemporaryFile() as tmp:
        return BytesIO(Path(self.exportToPDF(tmp.name, **_settings)).open('rb').read())

MappingWrapper

Bases: Generic[_MapType, _CIMType]

Internal wrapper class for wrapping existing objects with new functionality

Usage
>>> MappingWraper[mp.<type>, cim.<type>](mp.<type>)
Note

All

Methods:

Name Description
__eq__
__getattr__
__init__
__repr__

Attributes:

Name Type Description
cim _CIMType
cim_dict dict[str, Any] | None
parent

The parent object for the wrapper

unique_name str

Get the longName or name of the object. Use id for any object without a name attribute

uri str

Get the URI for the object or the id with :NO_URI at the end

Source code in src/arcpie/project.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
class MappingWrapper(Generic[_MapType, _CIMType]):
    """Internal wrapper class for wrapping existing objects with new functionality

    Usage:
        ```python
        >>> MappingWraper[mp.<type>, cim.<type>](mp.<type>)
        ```

    Note:
        All 
    """
    def __init__(self, obj: _MapType, parent: _MappingObject|Project|None=None) -> None:
        self._obj = obj
        self._parent = parent

    @property
    def parent(self):
        """The parent object for the wrapper

        `Project -> Map -> Layer`\n
        `Project -> Layout -> Map -> MapSeries`\n
        `Project -> Report`

        The general parent/child relationships are based on how you would access the object in ArcPro.
        Projects have maps, maps have layers, layouts have mapseries etc.
        """
        return self._parent

    @property
    def cim(self) -> _CIMType:
        try:
            return getattr(self._obj, 'getDefinition')('V3')
        except json.JSONDecodeError:
            print(f'Invalid layer definition found')
            return CIMDefinition(name='INVALID CIM') # pyright: ignore[reportReturnType]

    @property
    def unique_name(self) -> str:
        """Get the longName or name of the object. Use id for any object without a name attribute"""
        return getattr(self._obj, 'longName', None) or getattr(self._obj, 'name', None) or str(id(self._obj))

    @property
    def uri(self) -> str:
        """Get the URI for the object or the id with `:NO_URI` at the end"""
        _uri = getattr(self._obj, 'URI', None)
        if _uri is None:
            _uri = json.loads(self._obj._arc_object.GetCimJSONString())['uRI'] # type: ignore
        return _uri

    @property
    def cim_dict(self) -> dict[str, Any] | None:
        if _cim := self.cim:
            return json.loads(json.dumps(_cim, cls=CimJsonEncoder, indent=2))

    def __getattr__(self, attr: str) -> Any:
        return getattr(self._obj, attr)

    def __repr__(self) -> str:
        return f"{self._obj.__class__.__name__}({name_of(self, skip_uri=True)})"

    def __eq__(self, other: MappingWrapper[Any, Any] | Any) -> bool:
        if hasattr(other, '_obj'):
            return self._obj is getattr(other, '_obj', None)
        else:
            return super().__eq__(other)

cim property

cim_dict property

parent property

The parent object for the wrapper

Project -> Map -> Layer

Project -> Layout -> Map -> MapSeries

Project -> Report

The general parent/child relationships are based on how you would access the object in ArcPro. Projects have maps, maps have layers, layouts have mapseries etc.

unique_name property

Get the longName or name of the object. Use id for any object without a name attribute

uri property

Get the URI for the object or the id with :NO_URI at the end

__eq__(other)

Source code in src/arcpie/project.py
137
138
139
140
141
def __eq__(self, other: MappingWrapper[Any, Any] | Any) -> bool:
    if hasattr(other, '_obj'):
        return self._obj is getattr(other, '_obj', None)
    else:
        return super().__eq__(other)

__getattr__(attr)

Source code in src/arcpie/project.py
131
132
def __getattr__(self, attr: str) -> Any:
    return getattr(self._obj, attr)

__init__(obj, parent=None)

Source code in src/arcpie/project.py
88
89
90
def __init__(self, obj: _MapType, parent: _MappingObject|Project|None=None) -> None:
    self._obj = obj
    self._parent = parent

__repr__()

Source code in src/arcpie/project.py
134
135
def __repr__(self) -> str:
    return f"{self._obj.__class__.__name__}({name_of(self, skip_uri=True)})"

Project

Wrapper for an ArcGISProject (.aprx)

Usage
>>> prj = Project('<path/to/aprx>')
>>> lay = prj.layouts.get('My Layout')
>>> Path('My Layout.pdf').write_bytes(prj.layouts.get('My Layout').to_pdf())
4593490 # Bytes written
>>> for map in prj.maps:
...     print(f'{map.name} has {len(map.layers)} layers')
My Map has 5 layers
My Map 2 has 15 layers
Other Map has 56 layers

Methods:

Name Description
__getitem__

Resolve the name by looking in Maps, then Layouts, then Reports

__init__
__repr__
export_layers

Export all layers in the project to a structured directory of layerfiles

export_mapx

Export all maps to a directory

export_pagx

Export all layouts to a directory

get
import_layers

Import a structured directory of layerfiles generated with export_layers

import_mapx

Import a mapx file into this project

import_pagx

Import a pagx file into this project

refresh

Clear cached object managers

save

Save this project

save_as

Saves the project under a new name

Attributes:

Name Type Description
aprx ArcGISProject

Get the base ArcGISProject for the Project

broken_layers LayerManager

Get a LayerManager for all layers in the project with broken datasources

broken_tables TableManager

Get a TableManager for all tables in the project with broken datasources

layouts LayoutManager

Get a LayoutManager for the Project layouts

maps MapManager

Get a MapManager for the Project maps

name str

Get the file name of the wrapped aprx minus the file extension

reports ReportManager

Get a ReportManager for the Project reports

tree dict[str, Any]
Source code in src/arcpie/project.py
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
class Project:
    """Wrapper for an ArcGISProject (.aprx)

    Usage:
        ```python
        >>> prj = Project('<path/to/aprx>')
        >>> lay = prj.layouts.get('My Layout')
        >>> Path('My Layout.pdf').write_bytes(prj.layouts.get('My Layout').to_pdf())
        4593490 # Bytes written
        >>> for map in prj.maps:
        ...     print(f'{map.name} has {len(map.layers)} layers')
        My Map has 5 layers
        My Map 2 has 15 layers
        Other Map has 56 layers
        ```
    """
    def __init__(self, aprx_path: str|Path|Literal['CURRENT']='CURRENT') -> None:
        self._path = str(aprx_path)

    def __repr__(self) -> str:
        return f"Project({Path(self.aprx.filePath).stem}.aprx)"

    @property
    def name(self) -> str:
        """Get the file name of the wrapped aprx minus the file extension"""
        return Path(self.aprx.filePath).stem

    @property
    def aprx(self) -> ArcGISProject:
        """Get the base ArcGISProject for the Project"""
        return ArcGISProject(self._path)

    @cached_property
    def maps(self) -> MapManager:
        """Get a MapManager for the Project maps"""
        return MapManager(Map(m, self) for m in self.aprx.listMaps())

    @cached_property
    def layouts(self) -> LayoutManager:
        """Get a LayoutManager for the Project layouts"""
        return LayoutManager(Layout(l, self) for l in self.aprx.listLayouts())

    @cached_property
    def reports(self) -> ReportManager:
        """Get a ReportManager for the Project reports"""
        return ReportManager(Report(r, self) for r in self.aprx.listReports())

    @property
    def broken_layers(self) -> LayerManager:
        """Get a LayerManager for all layers in the project with broken datasources"""
        return LayerManager(Layer(l, self) for l in self.aprx.listBrokenDataSources() if isinstance(l, _Layer))

    @property
    def broken_tables(self) -> TableManager:
        """Get a TableManager for all tables in the project with broken datasources"""
        return TableManager(Table(t, self) for t in self.aprx.listBrokenDataSources() if isinstance(t, _Table))

    @property
    def tree(self) -> dict[str, Any]:
        return {
            repr(self) : 
                {
                    'maps': {
                        repr(m): 
                            {
                                'tables': m.tables.names,
                                'layers': m.layers.names,
                            }
                        for m in self.maps
                    },
                    'layouts': self.layouts.names,
                    'reports': self.reports.names,
                    'broken': {
                        'layers': self.broken_layers.names,
                        'tables': self.broken_layers.names,
                    }
                }
        }

    @overload
    def __getitem__(self, name: str) -> Map | Layout | Report: ...
    @overload
    def __getitem__(self, name: Wildcard) -> list[Map] | list[Layout] | list[Report]: ...
    def __getitem__(self, name: str | Wildcard) -> Any | list[Any]:
        """Resolve the name by looking in Maps, then Layouts, then Reports"""
        _obj = self.maps.get(name, None) or self.layouts.get(name, None) or self.reports.get(name, None)
        if _obj is None:
            raise KeyError(f'{name} not found in {self.name}')
        return _obj

    @overload
    def get(self, name: str, default: _Default) -> Map | Layout | Report | _Default: ...
    @overload
    def get(self, name: Wildcard, default: _Default) -> list[Map] | list[Layout] | list[Report] | _Default: ...
    def get(self, name: str | Wildcard, default: _Default=None) -> Any | _Default:
        try:
            return self[name]
        except KeyError:
            return default

    def save(self) -> None:
        """Save this project"""
        self.aprx.save()

    def save_as(self, path: Path|str) -> Project:
        """Saves the project under a new name

        Args:
            path (Path|str): The filepath of the new aprx

        Returns:
            (Project): A Project representing the new project file

        Note:
            Saving a Project as a new project will not update this instance, and instead returns a new
            Project instance targeted at the new file
        """
        path = Path(path)
        self.aprx.saveACopy(str(path.with_suffix(f'{path.suffix}.aprx')))
        return Project(path)

    def import_pagx(self, pagx: Path|str, *, reuse_existing_maps: bool=True) -> Layout:
        """Import a pagx file into this project

        Args:
            pagx (Path|str): The path to the pagx document

        Returns:
            (Layout): A Layout parented to this project
        """
        pagx = Path(pagx)
        if not pagx.suffix == '.pagx':
            raise ValueError(f'{pagx} is not a pagx file!')

        _imported = self.aprx.importDocument(str(pagx), reuse_existing_maps=reuse_existing_maps)
        # Ensure that the imported document is a Layout
        if not isinstance(_imported, _Layout):
            self.aprx.deleteItem(_imported)
            raise ValueError(f'{pagx} is not a valid pagx file!')

        self.refresh('layouts')
        return Layout(_imported, parent=self)

    def export_pagx(self, target_dir: Path|str) -> None:
        """Export all layouts to a directory"""
        target_dir = Path(target_dir)
        target_dir.mkdir(exist_ok=True, parents=True)
        for layout in self.layouts:
            (target_dir / f'{layout.unique_name}.pagx').write_text(json.dumps(layout.pagx, indent=2), encoding='utf-8')

    def import_mapx(self, mapx: Path|str) -> Map:
        """Import a mapx file into this project

        Args:
            mapx (Path|str): The path to the mapx document

        Returns:
            (Map): A Map parented to this project
        """
        mapx = Path(mapx)
        if not mapx.suffix == '.mapx':
            raise ValueError(f'{mapx} is not a mapx file!')

        _imported = self.aprx.importDocument(str(mapx))
        # Ensure that the imported document is a Map
        if not isinstance(_imported, _Map):
            self.aprx.deleteItem(_imported)
            raise ValueError(f'{mapx} is not a valid mapx file!')

        self.refresh('maps')
        return Map(_imported, parent=self)

    def export_mapx(self, target_dir: Path|str) -> None:
        """Export all maps to a directory"""
        target_dir = Path(target_dir)
        target_dir.mkdir(exist_ok=True, parents=True)
        for m in self.maps:
            (target_dir / f'{m.unique_name}.mapx').write_text(json.dumps(m.mapx, indent=2), encoding='utf-8')

    def export_layers(self, target_dir: Path|str, *, skip_groups: bool = False, skip_grouped: bool = False) -> None:
        """Export all layers in the project to a structured directory of layerfiles

        Args:
            target_dir (Path|str): The target directory to export the layerfiles to
            skip_groups (bool): Skip group layerfiles and export each layer individually in a group subdirectory (default: False)
            skip_grouped (bool): Inverse of skip groups and instead only exports the group lyrx, skipping the individual layers (default: False)
        """
        target_dir = Path(target_dir)
        for m in self.maps:
            m.export_assoc_lyrx(target_dir, skip_groups=skip_groups, skip_grouped=skip_grouped)

    def import_layers(self, src_dir: Path|str) -> None:
        """Import a structured directory of layerfiles generated with `export_layers`

        Args:
            src_dir (Path|str): A directory containing layer files in map directories and group directories

        Note:
            CIM changes require the APRX to be saved to take effect. If you are accessing this
            layer via a Project, use `project.save()` after importing the layerfile
        """
        src_dir = Path(src_dir)
        for m in self.maps:
            map_dir = src_dir / m.unique_name
            if not map_dir.exists():
                print(f'Map {m.unique_name} does not have a valid source in the source directory, skipping')
                continue
            m.import_assoc_lyrx(map_dir)

        self.refresh('layers')

    def refresh(self, *managers: str) -> None:
        """Clear cached object managers

        Args:
            *managers (*str): Optionally limit cache clearing to certain managers (attribute name)
        """
        for prop in list(self.__dict__):
            if prop.startswith('_') or managers and prop not in managers:
                continue # Skip private instance attributes and non-requested
            self.__dict__.pop(prop, None)

aprx property

Get the base ArcGISProject for the Project

broken_layers property

Get a LayerManager for all layers in the project with broken datasources

broken_tables property

Get a TableManager for all tables in the project with broken datasources

layouts cached property

Get a LayoutManager for the Project layouts

maps cached property

Get a MapManager for the Project maps

name property

Get the file name of the wrapped aprx minus the file extension

reports cached property

Get a ReportManager for the Project reports

tree property

__getitem__(name)

__getitem__(name: str) -> Map | Layout | Report
__getitem__(
    name: Wildcard,
) -> list[Map] | list[Layout] | list[Report]

Resolve the name by looking in Maps, then Layouts, then Reports

Source code in src/arcpie/project.py
784
785
786
787
788
789
def __getitem__(self, name: str | Wildcard) -> Any | list[Any]:
    """Resolve the name by looking in Maps, then Layouts, then Reports"""
    _obj = self.maps.get(name, None) or self.layouts.get(name, None) or self.reports.get(name, None)
    if _obj is None:
        raise KeyError(f'{name} not found in {self.name}')
    return _obj

__init__(aprx_path='CURRENT')

Source code in src/arcpie/project.py
717
718
def __init__(self, aprx_path: str|Path|Literal['CURRENT']='CURRENT') -> None:
    self._path = str(aprx_path)

__repr__()

Source code in src/arcpie/project.py
720
721
def __repr__(self) -> str:
    return f"Project({Path(self.aprx.filePath).stem}.aprx)"

export_layers(target_dir, *, skip_groups=False, skip_grouped=False)

Export all layers in the project to a structured directory of layerfiles

Parameters:

Name Type Description Default
target_dir Path | str

The target directory to export the layerfiles to

required
skip_groups bool

Skip group layerfiles and export each layer individually in a group subdirectory (default: False)

False
skip_grouped bool

Inverse of skip groups and instead only exports the group lyrx, skipping the individual layers (default: False)

False
Source code in src/arcpie/project.py
880
881
882
883
884
885
886
887
888
889
890
def export_layers(self, target_dir: Path|str, *, skip_groups: bool = False, skip_grouped: bool = False) -> None:
    """Export all layers in the project to a structured directory of layerfiles

    Args:
        target_dir (Path|str): The target directory to export the layerfiles to
        skip_groups (bool): Skip group layerfiles and export each layer individually in a group subdirectory (default: False)
        skip_grouped (bool): Inverse of skip groups and instead only exports the group lyrx, skipping the individual layers (default: False)
    """
    target_dir = Path(target_dir)
    for m in self.maps:
        m.export_assoc_lyrx(target_dir, skip_groups=skip_groups, skip_grouped=skip_grouped)

export_mapx(target_dir)

Export all maps to a directory

Source code in src/arcpie/project.py
873
874
875
876
877
878
def export_mapx(self, target_dir: Path|str) -> None:
    """Export all maps to a directory"""
    target_dir = Path(target_dir)
    target_dir.mkdir(exist_ok=True, parents=True)
    for m in self.maps:
        (target_dir / f'{m.unique_name}.mapx').write_text(json.dumps(m.mapx, indent=2), encoding='utf-8')

export_pagx(target_dir)

Export all layouts to a directory

Source code in src/arcpie/project.py
844
845
846
847
848
849
def export_pagx(self, target_dir: Path|str) -> None:
    """Export all layouts to a directory"""
    target_dir = Path(target_dir)
    target_dir.mkdir(exist_ok=True, parents=True)
    for layout in self.layouts:
        (target_dir / f'{layout.unique_name}.pagx').write_text(json.dumps(layout.pagx, indent=2), encoding='utf-8')

get(name, default=None)

get(
    name: str, default: _Default
) -> Map | Layout | Report | _Default
get(
    name: Wildcard, default: _Default
) -> list[Map] | list[Layout] | list[Report] | _Default
Source code in src/arcpie/project.py
795
796
797
798
799
def get(self, name: str | Wildcard, default: _Default=None) -> Any | _Default:
    try:
        return self[name]
    except KeyError:
        return default

import_layers(src_dir)

Import a structured directory of layerfiles generated with export_layers

Parameters:

Name Type Description Default
src_dir Path | str

A directory containing layer files in map directories and group directories

required
Note

CIM changes require the APRX to be saved to take effect. If you are accessing this layer via a Project, use project.save() after importing the layerfile

Source code in src/arcpie/project.py
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
def import_layers(self, src_dir: Path|str) -> None:
    """Import a structured directory of layerfiles generated with `export_layers`

    Args:
        src_dir (Path|str): A directory containing layer files in map directories and group directories

    Note:
        CIM changes require the APRX to be saved to take effect. If you are accessing this
        layer via a Project, use `project.save()` after importing the layerfile
    """
    src_dir = Path(src_dir)
    for m in self.maps:
        map_dir = src_dir / m.unique_name
        if not map_dir.exists():
            print(f'Map {m.unique_name} does not have a valid source in the source directory, skipping')
            continue
        m.import_assoc_lyrx(map_dir)

    self.refresh('layers')

import_mapx(mapx)

Import a mapx file into this project

Parameters:

Name Type Description Default
mapx Path | str

The path to the mapx document

required

Returns:

Type Description
Map

A Map parented to this project

Source code in src/arcpie/project.py
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
def import_mapx(self, mapx: Path|str) -> Map:
    """Import a mapx file into this project

    Args:
        mapx (Path|str): The path to the mapx document

    Returns:
        (Map): A Map parented to this project
    """
    mapx = Path(mapx)
    if not mapx.suffix == '.mapx':
        raise ValueError(f'{mapx} is not a mapx file!')

    _imported = self.aprx.importDocument(str(mapx))
    # Ensure that the imported document is a Map
    if not isinstance(_imported, _Map):
        self.aprx.deleteItem(_imported)
        raise ValueError(f'{mapx} is not a valid mapx file!')

    self.refresh('maps')
    return Map(_imported, parent=self)

import_pagx(pagx, *, reuse_existing_maps=True)

Import a pagx file into this project

Parameters:

Name Type Description Default
pagx Path | str

The path to the pagx document

required

Returns:

Type Description
Layout

A Layout parented to this project

Source code in src/arcpie/project.py
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
def import_pagx(self, pagx: Path|str, *, reuse_existing_maps: bool=True) -> Layout:
    """Import a pagx file into this project

    Args:
        pagx (Path|str): The path to the pagx document

    Returns:
        (Layout): A Layout parented to this project
    """
    pagx = Path(pagx)
    if not pagx.suffix == '.pagx':
        raise ValueError(f'{pagx} is not a pagx file!')

    _imported = self.aprx.importDocument(str(pagx), reuse_existing_maps=reuse_existing_maps)
    # Ensure that the imported document is a Layout
    if not isinstance(_imported, _Layout):
        self.aprx.deleteItem(_imported)
        raise ValueError(f'{pagx} is not a valid pagx file!')

    self.refresh('layouts')
    return Layout(_imported, parent=self)

refresh(*managers)

Clear cached object managers

Parameters:

Name Type Description Default
*managers *str

Optionally limit cache clearing to certain managers (attribute name)

()
Source code in src/arcpie/project.py
912
913
914
915
916
917
918
919
920
921
def refresh(self, *managers: str) -> None:
    """Clear cached object managers

    Args:
        *managers (*str): Optionally limit cache clearing to certain managers (attribute name)
    """
    for prop in list(self.__dict__):
        if prop.startswith('_') or managers and prop not in managers:
            continue # Skip private instance attributes and non-requested
        self.__dict__.pop(prop, None)

save()

Save this project

Source code in src/arcpie/project.py
801
802
803
def save(self) -> None:
    """Save this project"""
    self.aprx.save()

save_as(path)

Saves the project under a new name

Parameters:

Name Type Description Default
path Path | str

The filepath of the new aprx

required

Returns:

Type Description
Project

A Project representing the new project file

Note

Saving a Project as a new project will not update this instance, and instead returns a new Project instance targeted at the new file

Source code in src/arcpie/project.py
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
def save_as(self, path: Path|str) -> Project:
    """Saves the project under a new name

    Args:
        path (Path|str): The filepath of the new aprx

    Returns:
        (Project): A Project representing the new project file

    Note:
        Saving a Project as a new project will not update this instance, and instead returns a new
        Project instance targeted at the new file
    """
    path = Path(path)
    self.aprx.saveACopy(str(path.with_suffix(f'{path.suffix}.aprx')))
    return Project(path)

Report

Bases: MappingWrapper[Report, CIMReport], Report

Source code in src/arcpie/project.py
566
class Report(MappingWrapper[_Report, CIMReport], _Report): ...

ReportManager

Bases: Manager[Report]

Source code in src/arcpie/project.py
693
class ReportManager(Manager[Report]): ...

Table

Bases: MappingWrapper[Table, CIMStandaloneTable], Table

Methods:

Name Description
export_lyrx

Export the layer to a lyrx file in the target directory

import_lyrx

Import the table state from an lyrx file

Attributes:

Name Type Description
cim CIMStandaloneTable
lyrx dict[str, Any]
table Table

Get an arcpie.Table object from the TableLayer

Source code in src/arcpie/project.py
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
class Table(MappingWrapper[_Table, CIMStandaloneTable], _Table):
    @property
    def table(self) -> DataTable:
        """Get an `arcpie.Table` object from the TableLayer"""
        return DataTable.from_table(self)

    @property
    def cim(self) -> CIMStandaloneTable:
        return super().cim # pyright: ignore[reportReturnType]

    @property
    def lyrx(self) -> dict[str, Any]:
        _def = self.cim_dict
        _lyrx: dict[str, Any] = { # Base required keys for lyrx file
            'type': 'CIMLayerDocument',
            'tables': [self.uri],
            'tableDefinitions': [_def],
        }
        return _lyrx

    def export_lyrx(self, out_dir: Path|str) -> None:
        """Export the layer to a lyrx file in the target directory

        Args:
            out_dir (Path|str): The location to export the lyrx to
        """
        target = Path(out_dir) / f'{self.longName}.lyrx'
        # Make Containing directory for grouped layers
        target.parent.mkdir(exist_ok=True, parents=True)
        target.write_text(json.dumps(self.lyrx, indent=2), encoding='utf-8')

    def import_lyrx(self, lyrx: Path|str) -> None:
        """Import the table state from an lyrx file

        Args:
            lyrx (Path|str): The lyrx file to update this table with

        Note:
            CIM changes require the APRX to be saved to take effect. If you are accessing this
            layer via a Project, use `project.save()` after importing the layerfile
        """
        _lyrx = LayerFile(str(lyrx))
        _lyrx_layers = {t.longName: t for t in _lyrx.listTables()}
        for table in [self]:
            _lyrx_table = _lyrx_layers.get(table.longName)
            if not _lyrx_table:
                print(f'{self.longName} not found in {str(lyrx)}')
                continue
            # Update Connection
            _lyrx_table.updateConnectionProperties(None, table.connectionProperties) # type: ignore
            _lyrx_layer_cim = _lyrx_table.getDefinition('V3')
            self.setDefinition(_lyrx_layer_cim)

cim property

lyrx property

table property

Get an arcpie.Table object from the TableLayer

export_lyrx(out_dir)

Export the layer to a lyrx file in the target directory

Parameters:

Name Type Description Default
out_dir Path | str

The location to export the lyrx to

required
Source code in src/arcpie/project.py
533
534
535
536
537
538
539
540
541
542
def export_lyrx(self, out_dir: Path|str) -> None:
    """Export the layer to a lyrx file in the target directory

    Args:
        out_dir (Path|str): The location to export the lyrx to
    """
    target = Path(out_dir) / f'{self.longName}.lyrx'
    # Make Containing directory for grouped layers
    target.parent.mkdir(exist_ok=True, parents=True)
    target.write_text(json.dumps(self.lyrx, indent=2), encoding='utf-8')

import_lyrx(lyrx)

Import the table state from an lyrx file

Parameters:

Name Type Description Default
lyrx Path | str

The lyrx file to update this table with

required
Note

CIM changes require the APRX to be saved to take effect. If you are accessing this layer via a Project, use project.save() after importing the layerfile

Source code in src/arcpie/project.py
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
def import_lyrx(self, lyrx: Path|str) -> None:
    """Import the table state from an lyrx file

    Args:
        lyrx (Path|str): The lyrx file to update this table with

    Note:
        CIM changes require the APRX to be saved to take effect. If you are accessing this
        layer via a Project, use `project.save()` after importing the layerfile
    """
    _lyrx = LayerFile(str(lyrx))
    _lyrx_layers = {t.longName: t for t in _lyrx.listTables()}
    for table in [self]:
        _lyrx_table = _lyrx_layers.get(table.longName)
        if not _lyrx_table:
            print(f'{self.longName} not found in {str(lyrx)}')
            continue
        # Update Connection
        _lyrx_table.updateConnectionProperties(None, table.connectionProperties) # type: ignore
        _lyrx_layer_cim = _lyrx_table.getDefinition('V3')
        self.setDefinition(_lyrx_layer_cim)

TableManager

Bases: Manager[Table]

Source code in src/arcpie/project.py
697
class TableManager(Manager[Table]): ...

Wildcard

Bases: UserString

Clarify that the string passed to a Manager index is a wildcard so the type checker knows you're getting a Sequence back

Source code in src/arcpie/project.py
73
74
75
class Wildcard(UserString): 
    """Clarify that the string passed to a Manager index is a wildcard so the type checker knows you're getting a Sequence back"""
    pass

name_of(o, skip_uri=False, uri_only=False)

Handle the naming hierarchy of mapping objects URI -> longName -> name

Allow setting flags to get specific names

Note

If a URI is requested and no URI attribute is available in object, 'obj.name: NO URI(id(obj))' will be returned, e.g. 'my_bookmark: NO URI(1239012093)'

Source code in src/arcpie/project.py
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
def name_of(o: MappingWrapper[Any, Any], skip_uri: bool=False, uri_only: bool=False) -> str:
    """Handle the naming hierarchy of mapping objects URI -> longName -> name

    Allow setting flags to get specific names

    Note:
        If a URI is requested and no `URI` attribute is available in object, 
        `'obj.name: NO URI(id(obj))'` will be returned, e.g. `'my_bookmark: NO URI(1239012093)'`
    """
    _uri: str|None = o.uri if not skip_uri else None
    _long_name: str|None = getattr(o, 'longName', None) # longName will identify Grouped Layers
    _name: str|None = getattr(o, 'name', None)
    _id: str = str(id(o)) # Fallback to a locally unique id (should never happen)
    if uri_only:
        return _uri or f"{id(o)}:NO_URI"
    return _uri or _long_name or _name or _id