Skip to content

Field

CLASS DESCRIPTION
FA_Domain

Accepts a TypeVar Literal with valid domains

SchemaDocs

SchemaDocs = dict[str, str]

A mapping of fieldname -> field doc

FA_Domain dataclass

FA_Domain(field_domain: T)

Bases: FieldAnnotation

Accepts a TypeVar Literal with valid domains

parse_fields

parse_fields(
    table_def: TableDef,
) -> tuple[GeoType | None, dict[str, Field]]

Parse a table definition generated by yield_schema

PARAMETER DESCRIPTION

table_def

The table TypedDict with Annotated keys to parse

TYPE: TableDef

RETURNS DESCRIPTION
GeoType | None

A tuple containing None or the Feature Shape flag, and a mapping of fieldnames to field constructor args

dict[str, Field]

e.g. ('POLYLINE', {'Field1': {'field_type': 'TEXT', ...}, ...})

Note

None as the first return value indicates a Table or a shapeless featureclass (SHAPE@ required in the Schema)

Source code in src/arcpie/schema/field.py
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
def parse_fields(table_def: TableDef) -> tuple[GeoType | None, dict[str, Field]]:
    """Parse a table definition generated by `yield_schema`

    Args:
        table_def: The table TypedDict with Annotated keys to parse

    Returns:
        A tuple containing None or the Feature Shape flag, and a mapping of fieldnames to field constructor args 

        e.g. `('POLYLINE', {'Field1': {'field_type': 'TEXT', ...}, ...})`

    Note:
        `None` as the first return value indicates a Table or a shapeless featureclass (`SHAPE@` required in the Schema)
    """
    geo_type: GeoType | None = None
    annos = get_type_hints(table_def, include_extras=True)
    fields: dict[str, Field] = {}
    for f_name, f_detail in annos.items():
        # Resolve ForwardRef and make sure to include Annotated __metadata__
        if '@' in f_name:
            if f_name == 'SHAPE@':
                # Get the shape type
                geo_type = str(f_detail.__name__).upper() # type: ignore (Shape name is capital case)
                if geo_type == 'POINTGEOMETRY': # type: ignore (Edge Case)
                    geo_type = 'POINT'
            continue

        # Consume annotations to build FieldDef
        field_opts: Field = {
            prop.__slots__[0]: getattr(prop, prop.__slots__[0])
            for prop in f_detail.__metadata__ # type: ignore (Annotated access)
        }
        fields[f_name] = field_opts

    return (geo_type, fields)

parse_hierarchy

parse_hierarchy(
    root: type | ForwardRef, skip_annos: bool = True
) -> dict[str, Any]

Parse the root schema and resolve all forward references to Table definitions

Source code in src/arcpie/schema/field.py
319
320
321
322
323
324
325
326
327
328
329
330
def parse_hierarchy(root: type | ForwardRef, skip_annos: bool = True) -> dict[str, Any]:
    """Parse the root schema and resolve all forward references to Table definitions"""
    _parsed: dict[str, Any] = {}
    root_types = get_type_hints(root, include_extras=True)
    for item, item_type in root_types.items():
        if (item_type.__doc__ or '').startswith('FeatureDataset'):
            _parsed[item] = parse_hierarchy(item_type)
        if not (item_type.__doc__ or '').startswith('FeatureDataset'):
            if (item_type.__doc__ or '').startswith('Annotation') and skip_annos:
                continue
            _parsed[item] = parse_fields(item_type)
    return _parsed

yield_schema

yield_schema(
    fc: FeatureClass[Any, Any] | Table[Any],
    *,
    fallback_type: type = object,
    docs: SchemaDocs | None = None,
    include_shape_token: bool = True,
    include_oid_token: bool = True,
    default_doc: Callable[
        [Field], str
    ] = _default_field_doc,
) -> Iterator[str]

Yield the code for a FeatureClass schema

Args:
    fc: The FeatureClass/Table to generate a schema dict for
    fallback_type: The default type annotation for any fields that aren't mapped properly
    docs: Optional docs to include for each field (e.g. `{'FieldName': 'field doc', ...}`)
    include_shape_token: Include a `SHAPE@` key with the FeatureClass shape type (no effect on Tables)
    include_oid_token: Include the `OID@` key
    default_doc: A function that takes a Field dictionary and retuens a formatted doc (default: `k: v

...`)

Note:
    The schema type will be added as a __doc__ attribute to the definition
Source code in src/arcpie/schema/field.py
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
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
def yield_schema(fc: FeatureClass[Any, Any] | Table[Any],
                 *, 
                 fallback_type: type = object, 
                 docs: SchemaDocs | None = None,
                 include_shape_token: bool = True,
                 include_oid_token: bool = True,
                 default_doc: Callable[[Field], str]=_default_field_doc,
    ) -> Iterator[str]:
    """Yield the code for a FeatureClass schema

    Args:
        fc: The FeatureClass/Table to generate a schema dict for
        fallback_type: The default type annotation for any fields that aren't mapped properly
        docs: Optional docs to include for each field (e.g. `{'FieldName': 'field doc', ...}`)
        include_shape_token: Include a `SHAPE@` key with the FeatureClass shape type (no effect on Tables)
        include_oid_token: Include the `OID@` key
        default_doc: A function that takes a Field dictionary and retuens a formatted doc (default: `k: v\n\n...`)

    Note:
        The schema type will be added as a __doc__ attribute to the definition
    """
    if not docs:
        docs = {}

    bases = ['TypedDict']
    if include_oid_token:
        bases.append('OIDToken')
        docs['OID@'] = '"""OID Token for `arcpy.da` Cursors"""'

    if include_shape_token and isinstance(fc, FeatureClass):
        _shape = fc.describe.shapeType
        if _shape == 'Polygon':
            bases.append('PolygonShape')
        elif _shape == 'Point':
            bases.append('PointShape')
        elif _shape == 'Polyline':
            bases.append('PolylineShape')
        elif _shape == 'Multipoint':
            bases.append('MultiPointShape')
        elif _shape == 'MultiPatch':
            bases.append('MultiPatchShape')
        else:
            bases.append('GeometryShape')

        docs['SHAPE@'] = f'"""Shape Token for `arcpy.da` Cursors: {_shape.__class__.__name__}"""'

    if len(bases) > 1:
        # Don't bother inheriting TypedDict directly if additional 
        # schema tokens are inherited
        bases = bases[1:]

    yield f"class {fc.name}({', '.join(bases)}):"
    yield f'    """{getattr(fc.describe, 'featureType', 'Table')}"""'

    # Sort the defs by name to make schema diffing more reliable
    for f_name, f_def in sorted(fc.field_defs.items(), key=lambda fd: fd[0]):

        f_type = f_def.get('field_type')
        f_pytype = fallback_type
        if f_type:
            f_pytype = FIELD_TYPE_MAP.get(f_type, fallback_type)
        f_length = f_def.get('field_length')
        f_precision = f_def.get('field_precision')
        f_scale = f_def.get('field_scale')
        f_alias = f_def.get('field_alias')
        if f_alias == f_name:
            # Only set an alias if it's different
            f_alias = None

        # By default, fields are nullable and required
        f_is_nullable = f_def.get('field_is_nullable', True)
        f_is_required = f_def.get('field_is_required', True)
        f_domain = f_def.get('field_domain')
        f_default = f_def.get('field_default')
        if isinstance(f_default, str):
            f_default = repr(f_default)

        yield f"    {f_name}: Annotated[{f_pytype.__name__},"
        if f_type:
            yield f"        FA_Type({repr(f_type)}),"
        if f_alias:
            yield f"        FA_Alias({repr(f_alias)}),"
        if f_default:
            yield f"        FA_Default({f_default}),"
        if f_domain:
            yield f"        FA_Domain({repr(f_domain)}),"
        if f_length:
            yield f"        FA_Length({f_length}),"
        if f_precision:
            yield f"        FA_Precision({f_precision}),"
        if f_scale:
            yield f"        FA_Scale({f_scale}),"
        if f_is_nullable == 'NULLABLE':
            yield f"        FA_Nullable(),"
        if f_is_required == 'REQUIRED':
            yield f"        FA_Required(),"
        yield "    ]"
        if docs:
            f_doc: str = docs.get(f_name) or default_doc(f_def)
        else:
            f_doc: str = default_doc(f_def)
        if f_doc: # Don't yield an empty string
            yield f'    {f_doc}'
        yield ""