### Calculate product of prime factors using Counter Source: https://ufolib2.readthedocs.io/en/latest/_modules/collections.html Example demonstrating the use of elements() with math.prod to reconstruct a number from its prime factors. ```python import math prime_factors = Counter({2: 2, 3: 3, 17: 1}) math.prod(prime_factors.elements()) ``` -------------------------------- ### Glyph Object Usage Examples Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/glyph.html Demonstrates how to interact with the Glyph object using list-like operations to access and iterate over contours. ```python contour = glyph[0] ``` ```python for contour in glyph: ... ``` ```python contourCount = len(glyph) ``` ```python exists = contour in glyph ``` -------------------------------- ### ufoLib2 Attributes and Methods (X) Source: https://ufolib2.readthedocs.io/en/latest/genindex.html Details attributes starting with 'X' in ufoLib2, including coordinates for Anchor, Guideline, Point, and BoundingBox objects, as well as the xHeight property of Info objects. ```APIDOC ## Attributes and Methods (X) ### Description This section details attributes starting with 'X' in the ufoLib2 library. ### Attributes - **x** (ufoLib2.objects.Anchor attribute) - Also applicable to: - ufoLib2.objects.Guideline attribute - ufoLib2.objects.Point attribute - **xHeight** (ufoLib2.objects.Info attribute) - **xMax** (ufoLib2.objects.misc.BoundingBox attribute) - **xMin** (ufoLib2.objects.misc.BoundingBox attribute) ``` -------------------------------- ### LayerSet Usage Examples Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/layerSet.html Common operations for interacting with a LayerSet instance, including counting, iteration, existence checks, retrieval, and deletion. ```python layerCount = len(font.layers) ``` ```python for layer in font.layers: ... ``` ```python exists = "myLayerName" in font.layers ``` ```python font.layers["myLayerName"] ``` ```python del font.layers["myLayerName"] ``` -------------------------------- ### Begin a new contour path Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/pointPens/glyphPointPen.html Starts a new contour path. This method should be called before adding points to a contour. An optional identifier can be provided for the contour. ```python def beginPath(self, identifier: str | None = None, **kwargs: Any) -> None: self._contour = Contour(identifier=identifier) ``` -------------------------------- ### Get N most common elements from a string Source: https://ufolib2.readthedocs.io/en/latest/_modules/collections.html Example of using most_common(n) with a Counter initialized from a string. ```python Counter('abracadabra').most_common(3) ``` -------------------------------- ### Image Object Initialization Source: https://ufolib2.readthedocs.io/en/latest/reference.html Shows how to create an Image object, which represents a background image reference with optional transformation and color. ```python from ufoLib2.objects import Image image = Image(fileName='my_image.png', transformation=(1, 0, 0, 1, 10, 20), color='red') ``` -------------------------------- ### Implement DataStore Factory and Abstract Methods Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/misc.html Class methods for instantiation and abstract methods for data handling operations. ```python @classmethod def read(cls: type[Tds], reader: UFOReader, lazy: bool = True) -> Tds: """Instantiate the data store from a :class:`fontTools.ufoLib.UFOReader`.""" self = cls() for fileName in cls.list_contents(reader): if lazy: self._data[fileName] = _DATA_NOT_LOADED else: self._data[fileName] = cls.read_data(reader, fileName) self._lazy = lazy if lazy: self._reader = reader return self @staticmethod @abstractmethod def list_contents(reader: UFOReader) -> list[str]: """Returns a list of POSIX filename strings in the data store.""" ... @staticmethod @abstractmethod def read_data(reader: UFOReader, filename: str) -> bytes: """Returns the data at filename within the store.""" ... @staticmethod @abstractmethod def write_data(writer: UFOWriter, filename: str, data: bytes) -> None: """Writes the data to filename within the store.""" ... @staticmethod @abstractmethod def remove_data(writer: UFOWriter, filename: str) -> None: """Remove the data at filename within the store.""" ... ``` -------------------------------- ### Get Glyph Count in Layer Source: https://ufolib2.readthedocs.io/en/latest/reference.html Use the len() function to get the number of glyphs in a layer. This is useful for understanding the size of the layer. ```python glyphCount = len(layer) ``` -------------------------------- ### BoundingBox Object Initialization Source: https://ufolib2.readthedocs.io/en/latest/reference.html Demonstrates the creation of a BoundingBox object, which stores the minimum and maximum x and y coordinates. ```python from ufoLib2.objects import BoundingBox bounding_box = BoundingBox(xMin=0.0, yMin=0.0, xMax=100.0, yMax=200.0) ``` -------------------------------- ### Get Pen and PointPen Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/glyph.html Retrieves pens for drawing into the glyph. ```python [docs] def getPen(self) -> AbstractPen: """Returns a pen for others to draw into self.""" pen = SegmentToPointPen(self.getPointPen()) return pen [docs] def getPointPen(self) -> AbstractPointPen: """Returns a point pen for others to draw points into self.""" pointPen = GlyphPointPen(self) return pointPen ``` -------------------------------- ### GET /loadGlyph Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/layer.html Loads and returns a Glyph object by its name. ```APIDOC ## GET /loadGlyph ### Description Loads a specific glyph from the layer by name and returns the Glyph object. ### Method GET ### Parameters #### Query Parameters - **name** (str) - Required - The name of the glyph to load. ### Response #### Success Response (200) - **glyph** (Glyph) - The loaded Glyph object. ``` -------------------------------- ### Manage Glyph Guidelines with objectLib Source: https://ufolib2.readthedocs.io/en/latest/reference.html Demonstrates how to associate custom data with glyph guidelines using the objectLib method. This is useful for storing metadata specific to each guideline. ```python >>> from ufoLib2.objects import Font, Guideline >>> font = Font() >>> glyph = font.newGlyph("a") >>> glyph.guidelines = [Guideline(x=100)] >>> guideline_lib = glyph.objectLib(glyph.guidelines[0]) >>> guideline_lib["com.test.foo"] = 1234 >>> guideline_id = glyph.guidelines[0].identifier >>> assert guideline_id is not None >>> assert glyph.lib["public.objectLibs"][guideline_id] is guideline_lib ``` -------------------------------- ### GET /layer/glyph Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/layer.html Retrieves a specific glyph from the layer by its name. ```APIDOC ## GET /layer/glyph ### Description Retrieves a Glyph object from the layer. If the glyph is not loaded, it triggers a load operation. ### Method GET ### Parameters #### Path Parameters - **name** (str) - Required - The name of the glyph to retrieve. ### Response #### Success Response (200) - **glyph** (Glyph) - The requested Glyph object. ``` -------------------------------- ### Counter Class Initialization Source: https://ufolib2.readthedocs.io/en/latest/_modules/collections.html Demonstrates how to initialize a Counter object from various sources: an iterable, a mapping, or keyword arguments. ```APIDOC ## Counter Class Initialization ### Description Initializes a new, empty Counter object. If an iterable or mapping is provided, it counts elements from the input. ### Method `__init__(self, iterable=None, /, **kwds)` ### Parameters - `iterable` (iterable, optional): An iterable whose elements will be counted. - `kwds`: Keyword arguments where keys are elements and values are their counts. ### Request Example ```python # Initialize from an iterable c = Counter('gallahad') # Initialize from a mapping c = Counter({'a': 4, 'b': 2}) # Initialize from keyword arguments c = Counter(a=4, b=2) ``` ### Response - `Counter`: An instance of the Counter class with elements and their counts. ``` -------------------------------- ### Get the total count of all elements Source: https://ufolib2.readthedocs.io/en/latest/_modules/collections.html Calculate the sum of all counts in the Counter. ```python sum(c.values()) ``` -------------------------------- ### Initialize UserDict Source: https://ufolib2.readthedocs.io/en/latest/_modules/collections.html Initializes a UserDict instance, optionally with an existing dictionary or keyword arguments. The data is stored internally in a dictionary. ```python def __init__(self, dict=None, /, **kwargs): self.data = {} if dict is not None: self.update(dict) if kwargs: self.update(kwargs) ``` -------------------------------- ### Get Layer Count Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/layerSet.html Returns the total number of layers in the LayerSet. ```python def __len__(self) -> int: return len(self._layers) ``` -------------------------------- ### Interact with DataSet objects Source: https://ufolib2.readthedocs.io/en/latest/reference.html Demonstrates how to use the DataSet class as a dictionary to store and retrieve binary data associated with a font. ```python >>> from ufoLib2 import Font >>> font = Font() >>> font.data["test.txt"] = b"123" >>> font.data["directory/my_binary_blob.bin"] = b"456" >>> font.data["test.txt"] b'123' >>> del font.data["test.txt"] >>> list(font.data.items()) [('directory/my_binary_blob.bin', b'456')] ``` -------------------------------- ### Get layer count Source: https://ufolib2.readthedocs.io/en/latest/reference.html Retrieve the total number of layers present in the font. ```python layerCount = len(font.layers) ``` -------------------------------- ### Get the sum of counts Source: https://ufolib2.readthedocs.io/en/latest/_modules/collections.html The total() method calculates the sum of all counts in the Counter. ```python c.total() ``` -------------------------------- ### OrderedDict Initialization Source: https://ufolib2.readthedocs.io/en/latest/_modules/collections.html Details on how to initialize an OrderedDict object. ```APIDOC ## __new__(cls, /, *args, **kwds) ### Description Create the ordered dict object and set up the underlying structures. ### Method `__new__` ### Parameters None ### Request Example ```python # No direct example for __new__ as it's called internally. # Initialization is typically done via __init__. ``` ### Response #### Success Response (200) An instance of OrderedDict. #### Response Example ```json { "instance": "OrderedDict object" } ``` ## __init__(self, other=(), /, **kwds) ### Description Initialize an ordered dictionary. The signature is the same as regular dictionaries. Keyword argument order is preserved. ### Method `__init__` ### Parameters - **other** (iterable, optional) - An iterable of key-value pairs or another dictionary. - **kwds** (keyword arguments, optional) - Key-value pairs to initialize the dictionary with. ### Request Example ```python ordered_dict = OrderedDict([('a', 1), ('b', 2)], c=3) ``` ### Response #### Success Response (200) None (initializes the object in-place). #### Response Example ```json { "status": "initialized" } ``` ``` -------------------------------- ### List all unique elements Source: https://ufolib2.readthedocs.io/en/latest/_modules/collections.html Get a sorted list of all unique elements present in the Counter. ```python sorted(c) ``` -------------------------------- ### Implement DataStore Utility and Mapping Methods Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/misc.html Methods for unlazifying data and standard MutableMapping interface implementations. ```python def unlazify(self) -> None: """Load all data into memory.""" if self._lazy and self._reader is not None: for _ in self.items(): pass self._lazy = False __deepcopy__ = _deepcopy_unlazify_attrs __getstate__ = _getstate_unlazify_attrs __setstate__ = _setstate_attrs # MutableMapping methods def __len__(self) -> int: return len(self._data) def __iter__(self) -> Iterator[str]: return iter(self._data) def __getitem__(self, fileName: str) -> bytes: data_object = self._data[fileName] if data_object is _DATA_NOT_LOADED: data_object = self._data[fileName] = self.read_data(self._reader, fileName) return data_object def __setitem__(self, fileName: str, data: bytes) -> None: # should we forbid overwrite? self._data[fileName] = data if fileName in self._scheduledForDeletion: self._scheduledForDeletion.remove(fileName) def __delitem__(self, fileName: str) -> None: del self._data[fileName] self._scheduledForDeletion.add(fileName) def __repr__(self) -> str: n = len(self._data) return "<{}.{} ({}) at {}>".format( self.__class__.__module__, self.__class__.__name__, "empty" if n == 0 else "{} file{}".format(n, "s" if n > 1 else ""), hex(id(self)), ) ``` -------------------------------- ### GlyphPointPen Methods Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/pointPens/glyphPointPen.html Methods for managing glyph construction including path initialization, point addition, and component insertion. ```APIDOC ## beginPath ### Description Starts a new contour within the glyph. ### Parameters #### Keyword Arguments - **identifier** (str) - Optional - Unique identifier for the contour. ## endPath ### Description Finalizes the current contour and appends it to the glyph. ## addPoint ### Description Adds a point to the current contour. ### Parameters - **pt** (tuple[float, float]) - Required - The (x, y) coordinates of the point. - **segmentType** (str) - Optional - The type of segment (e.g., 'move', 'line', 'curve'). - **smooth** (bool) - Optional - Whether the point is smooth. - **name** (str) - Optional - Name of the point. - **identifier** (str) - Optional - Unique identifier for the point. ## addComponent ### Description Adds a component to the glyph. ### Parameters - **baseGlyph** (str) - Required - The name of the base glyph. - **transformation** (Transform) - Required - The transformation matrix applied to the component. - **identifier** (str) - Optional - Unique identifier for the component. ``` -------------------------------- ### Get the three most common elements Source: https://ufolib2.readthedocs.io/en/latest/_modules/collections.html Retrieve the N most common elements and their counts from the Counter. ```python c.most_common(3) ``` -------------------------------- ### POST /info/read Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/info.html Instantiates an Info object from a provided UFOReader instance. ```APIDOC ## POST /info/read ### Description Reads font information from a UFOReader and populates a new Info object instance. ### Method POST ### Parameters #### Request Body - **reader** (UFOReader) - Required - The UFOReader instance to read data from. ### Response #### Success Response (200) - **Info** (Object) - Returns a populated Info object. ``` -------------------------------- ### GET /getTopMargin Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/glyph.html Retrieves the space in font units from the top of the canvas to the top of the glyph. ```APIDOC ## GET /getTopMargin ### Description Returns the space in font units from the top of the canvas to the top of the glyph. ### Parameters #### Query Parameters - **layer** (GlyphSet) - Optional - The layer of the glyph to look up components. ### Response #### Success Response (200) - **margin** (float) - The top margin in font units. ``` -------------------------------- ### GET /getBottomMargin Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/glyph.html Retrieves the space in font units from the bottom of the canvas to the bottom of the glyph. ```APIDOC ## GET /getBottomMargin ### Description Returns the space in font units from the bottom of the canvas to the bottom of the glyph. ### Parameters #### Query Parameters - **layer** (GlyphSet) - Optional - The layer of the glyph to look up components. ### Response #### Success Response (200) - **margin** (float) - The bottom margin in font units. ``` -------------------------------- ### Creating and Using a namedtuple Source: https://ufolib2.readthedocs.io/en/latest/_modules/collections.html Demonstrates basic instantiation, attribute access, and unpacking of a namedtuple. Useful for creating simple, immutable data structures. ```python >>> Point = namedtuple('Point', ['x', 'y']) >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional args or keywords >>> p[0] + p[1] # indexable like a plain tuple 33 >>> x, y = p # unpack like a regular tuple >>> x, y (11, 22) >>> p.x + p.y # fields also accessible by name 33 ``` -------------------------------- ### UserString Initialization Source: https://ufolib2.readthedocs.io/en/latest/_modules/collections.html Initializes a UserString object from a string, another UserString, or any object convertible to a string. ```python class UserString(_collections_abc.Sequence): def __init__(self, seq): if isinstance(seq, str): self.data = seq elif isinstance(seq, UserString): self.data = seq.data[:] else: self.data = str(seq) ``` -------------------------------- ### Get Layer Names Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/layerSet.html Returns a set-like view of all layer names present in the LayerSet. ```python def keys(self) -> AbstractSet[str]: return self._layers.keys() ``` -------------------------------- ### GET /getLeftMargin Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/glyph.html Retrieves the space in font units from the point of origin to the left side of the glyph. ```APIDOC ## GET /getLeftMargin ### Description Returns the space in font units from the point of origin to the left side of the glyph. ### Parameters #### Query Parameters - **layer** (GlyphSet) - Optional - The layer of the glyph to look up components. ### Response #### Success Response (200) - **margin** (float) - The left margin in font units. ``` -------------------------------- ### Implement DataStore Write Method Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/misc.html Writes the data store to a UFOWriter, handling in-place updates and full exports. ```python def write(self, writer: UFOWriter, saveAs: bool | None = None) -> None: """Write the data store to a :class:`fontTools.ufoLib.UFOWriter`.""" if saveAs is None: saveAs = self._reader is not writer # if in-place, remove deleted data if not saveAs: for fileName in self._scheduledForDeletion: self.remove_data(writer, fileName) # Write data. Iterating over _data.items() prevents automatic loading. for fileName, data in self._data.items(): # Two paths: # 1) We are saving in-place. Only write to disk what is loaded, it # might be modified. # 2) We save elsewhere. Load all data files to write them back out. # XXX: Move write_data into `if saveAs` branch to simplify code? if data is _DATA_NOT_LOADED: ``` -------------------------------- ### Instantiate Glyph Object Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/layer.html Returns a new, empty Glyph instance. This is a compatibility method for defcon. ```python def instantiateGlyphObject(self) -> Glyph: """Returns a new Glyph instance. |defcon_compat| """ return Glyph() ``` -------------------------------- ### Get Glyph Bounds Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/glyph.html Calculates the bounding box of the glyph, requiring a layer for component-based glyphs. ```python [docs] def getBounds(self, layer: GlyphSet | None = None) -> BoundingBox | None: """Returns the (xMin, yMin, xMax, yMax) bounding box of the glyph, taking the actual contours into account. Args: layer: The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs. """ if layer is None and self.components: raise TypeError("layer is required to compute bounds of components") return getBounds(self, layer) ``` -------------------------------- ### Initialize GlyphPointPen Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/pointPens/glyphPointPen.html Initializes the GlyphPointPen with a target glyph object. This pen is used to draw contours and components onto the provided glyph. ```python from __future__ import annotations from typing import TYPE_CHECKING, Any from fontTools.misc.transform import Transform from fontTools.pens.pointPen import AbstractPointPen from ufoLib2.objects.component import Component from ufoLib2.objects.contour import Contour from ufoLib2.objects.point import Point if TYPE_CHECKING: from ufoLib2.objects.glyph import Glyph class GlyphPointPen(AbstractPointPen): # type: ignore """A point pen. See :mod:`fontTools.pens.basePen` and :mod:`fontTools.pens.pointPen` for an introduction to pens. """ __slots__ = "_glyph", "_contour" def __init__(self, glyph: Glyph) -> None: self._glyph: Glyph = glyph self._contour: Contour | None = None ``` -------------------------------- ### Get Number of Glyphs in Layer Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/layer.html Returns the total number of glyphs currently stored in the layer. ```python def __len__(self) -> int: return len(self._glyphs) ``` -------------------------------- ### Initialize a Counter from keyword arguments Source: https://ufolib2.readthedocs.io/en/latest/_modules/collections.html Create a new Counter object initialized with counts from keyword arguments. ```python c = Counter(a=4, b=2) ``` -------------------------------- ### Invalid Annotated Usage with TypeVarTuple Source: https://ufolib2.readthedocs.io/en/latest/_modules/typing.html Example of an invalid attempt to use Annotated with an unpacked TypeVarTuple. ```python type Variadic[*Ts] = Annotated[*Ts, Ann1] # NOT valid ``` -------------------------------- ### LayerSet Instance Methods Source: https://ufolib2.readthedocs.io/en/latest/reference.html Details on instance methods for interacting with LayerSet objects. ```APIDOC ## LayerSet Instance Methods ### `get(_name : str_, _default : T | None = None_)` **Description**: Retrieves a layer by name, returning a default value if not found. ### `json_dump(_fp : PathLike | BinaryIO_, _indent : int | None = None_, _sort_keys : bool = False_, _** kwargs: Any_)` **Description**: Dumps the LayerSet object to a JSON file-like object. ### `json_dumps(_indent : int | None = None_, _sort_keys : bool = False_, _** kwargs: Any_)` **Description**: Returns the LayerSet object as a JSON formatted string. ### `json_load(_*_ , ___callback : Callable[..._, _T] =_, _**kwargs : Any_)` **Description**: Loads LayerSet data from a JSON source. ### `json_loads(_*_ , ___callback : Callable[..._, _T] =_, _**kwargs : Any_)` **Description**: Loads LayerSet data from a JSON string. ### `keys()` **Description**: Returns a set of all layer names in the LayerSet. ### `msgpack_dump(_fp : PathLike | BinaryIO_, _** kwargs: Any_)` **Description**: Dumps the LayerSet object to a MessagePack file-like object. ### `msgpack_dumps(_** kwargs: Any_)` **Description**: Returns the LayerSet object as a MessagePack formatted bytes. ### `msgpack_load(_*_ , ___callback : Callable[..._, _T] =_, _**kwargs : Any_)` **Description**: Loads LayerSet data from a MessagePack source. ### `msgpack_loads(_*_ , ___callback : Callable[..._, _T] =_, _**kwargs : Any_)` **Description**: Loads LayerSet data from MessagePack bytes. ### `newLayer(_name : str_, _** kwargs: Any_)` **Description**: Creates and returns a new named layer. **Parameters**: - `name` (str) - The name for the new layer. - `kwargs` - Arguments passed to the constructor of Layer. ### `renameGlyph(_name : str_, _newName : str_, _overwrite : bool = False_)` **Description**: Renames a glyph across all layers. **Parameters**: - `name` (str) - The current name of the glyph. - `newName` (str) - The new name for the glyph. - `overwrite` (bool, optional) - If False, raises an exception if `newName` is already taken in any layer. If True, overwrites the existing glyph. Defaults to False. ### `renameLayer(_name : str_, _newName : str_, _overwrite : bool = False_)` **Description**: Renames a layer. **Parameters**: - `name` (str) - The current name of the layer. - `newName` (str) - The new name for the layer. - `overwrite` (bool, optional) - If False, raises an exception if `newName` is already taken. If True, overwrites the existing layer. Defaults to False. ### `unlazify()` **Description**: Loads all layers into memory, resolving any lazy loading. ### `write(_writer : UFOWriter_, _saveAs : bool | None = None_)` **Description**: Writes the LayerSet to a `fontTools.ufoLib.UFOWriter`. **Parameters**: - `writer` (UFOWriter) - The writer object to write to. - `saveAs` (bool | None, optional) - If True, tells the writer to save out-of-place. If False, tells the writer to save in-place. Affects resource cleanup before writing. ``` -------------------------------- ### Get the count of a specific element Source: https://ufolib2.readthedocs.io/en/latest/_modules/collections.html Access the count of a specific element using dictionary-like key access. ```python c['a'] ``` -------------------------------- ### Load C helper function for counting Source: https://ufolib2.readthedocs.io/en/latest/_modules/collections.html Attempts to import a C-optimized helper function for counting elements. If unavailable, it falls back to the Python implementation. ```python from _collections import _count_elements ``` -------------------------------- ### Get Kerning from Font object Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/font.html Internal helper function to retrieve the kerning object from a Font instance. ```python def _get_kerning(self: Font) -> Kerning: return self._kerning ``` -------------------------------- ### Count elements from a string Source: https://ufolib2.readthedocs.io/en/latest/_modules/collections.html Demonstrates initializing a Counter by counting characters in a string. ```python c = Counter('abcdeabcdabcaba') ``` -------------------------------- ### Get Layer by Name Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/layerSet.html Retrieves a layer by its name. If the layer is not loaded (lazy mode), it will be loaded before being returned. ```python def __getitem__(self, name: str) -> Layer: layer_object = self._layers[name] if layer_object is _LAYER_NOT_LOADED: return self.loadLayer(name) return layer_object ``` -------------------------------- ### Initializing _GenericAlias Source: https://ufolib2.readthedocs.io/en/latest/_modules/typing.html The constructor for _GenericAlias takes an origin type, arguments, and optional instantiation and name. Arguments are converted to a tuple, handling ellipsis. ```python def __init__(self, origin, args, *, inst=True, name=None): super().__init__(origin, inst=inst, name=name) if not isinstance(args, tuple): args = (args,) self.__args__ = tuple(... if a is _TypingEllipsis else a for a in args) self.__parameters__ = _collect_parameters(args) if not name: self.__module__ = origin.__module__ ``` -------------------------------- ### UserString Suffix Check Source: https://ufolib2.readthedocs.io/en/latest/_modules/collections.html Checks if the UserString ends with a specified suffix, with optional start and end indices. ```python def endswith(self, suffix, start=0, end=_sys.maxsize): return self.data.endswith(suffix, start, end) ``` -------------------------------- ### UserString Substring Counting Source: https://ufolib2.readthedocs.io/en/latest/_modules/collections.html Counts the occurrences of a substring within the UserString, with optional start and end indices. ```python def count(self, sub, start=0, end=_sys.maxsize): if isinstance(sub, UserString): sub = sub.data return self.data.count(sub, start, end) ``` -------------------------------- ### Implement DataStore Equality Methods Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/misc.html Custom equality and inequality methods that handle un-lazifying the data stores before comparison. ```python def __eq__(self, other: object) -> bool: # same as attrs-defined __eq__ method, only that it un-lazifies DataStores # if needed. # NOTE: Avoid isinstance check that mypy recognizes because we don't want to # test possible Font subclasses for equality. if other.__class__ is not self.__class__: return NotImplemented other = cast(DataStore, other) for data_store in (self, other): if data_store._lazy: data_store.unlazify() return self._data == other._data def __ne__(self, other: object) -> bool: result = self.__eq__(other) if result is NotImplemented: return NotImplemented return not result ``` -------------------------------- ### Getting the Number of Points in a Contour Source: https://ufolib2.readthedocs.io/en/latest/reference.html Use the len() function to determine the total number of points within a Contour. ```python pointCount = len(contour) ``` -------------------------------- ### GET /getRightMargin Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/glyph.html Retrieves the space in font units from the glyph's advance width to the right side of the glyph. ```APIDOC ## GET /getRightMargin ### Description Returns the space in font units from the glyph's advance width to the right side of the glyph. ### Parameters #### Query Parameters - **layer** (GlyphSet) - Optional - The layer of the glyph to look up components. ### Response #### Success Response (200) - **margin** (float) - The right margin in font units. ``` -------------------------------- ### Import and Validation Logic for Info Objects Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/info.html Initializes the module with necessary imports and defines a validator for ensuring attributes remain non-negative. ```python from __future__ import annotations from enum import IntEnum from functools import partial from typing import Any, Callable, List, Mapping, Optional, Sequence, TypeVar import attrs from attrs import define, field from fontTools.ufoLib import UFOReader from ufoLib2.objects.guideline import Guideline from ufoLib2.objects.misc import AttrDictMixin from ufoLib2.serde import serde from .woff import ( WoffMetadataCopyright, WoffMetadataCredit, WoffMetadataCredits, WoffMetadataDescription, WoffMetadataExtension, WoffMetadataExtensionItem, WoffMetadataExtensionName, WoffMetadataExtensionValue, WoffMetadataLicense, WoffMetadataLicensee, WoffMetadataText, WoffMetadataTrademark, WoffMetadataUniqueID, WoffMetadataVendor, ) __all__ = ( "Info", "GaspRangeRecord", "NameRecord", "WidthClass", "WoffMetadataCopyright", "WoffMetadataCredit", "WoffMetadataCredits", "WoffMetadataDescription", "WoffMetadataExtension", "WoffMetadataExtensionItem", "WoffMetadataExtensionName", "WoffMetadataExtensionValue", "WoffMetadataLicense", "WoffMetadataLicensee", "WoffMetadataText", "WoffMetadataTrademark", "WoffMetadataUniqueID", "WoffMetadataVendor", ) def _positive(instance: Any, attribute: Any, value: int) -> None: if value < 0: raise ValueError( "'{name}' must be at least 0 (got {value!r})".format( name=attribute.name, value=value ) ) _optional_positive = attrs.validators.optional(_positive) ``` -------------------------------- ### Get Layer Order Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/layerSet.html Returns a list representing the current order of layers. Modifications to the returned list do not affect the LayerSet. ```python @property def layerOrder(self) -> list[str]: """The font's layer order. Getter: Returns the font's layer order. Note: The getter always returns a new list, modifications to it do not change the LayerSet. Setter: Sets the font's layer order. The set order value must contain all layers that are present in the LayerSet. """ return list(self._layers) ``` -------------------------------- ### DataStore: File Names Property Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/misc.html Returns a list of filenames currently stored in the DataStore. ```python return list(self._data.keys()) ``` -------------------------------- ### Append Guideline Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/font.html Adds a guideline to the font's global guidelines list, creating the list if necessary. ```python def appendGuideline(self, guideline: Guideline | Mapping[str, Any]) -> None: """Appends a guideline to the list of the font's global guidelines. Creates the global guideline list unless it already exists. Args: guideline: A :class:`.Guideline` object or a mapping for the Guideline constructor. """ if not isinstance(guideline, Guideline): if not isinstance(guideline, Mapping): raise TypeError( "Expected Guideline object or a Mapping for the ", f"Guideline constructor, found {type(guideline).__name__}", ) guideline = Guideline(**guideline) if self.info.guidelines is None: self.info.guidelines = [] self.info.guidelines.append(guideline) ``` -------------------------------- ### UserDict Get Item Source: https://ufolib2.readthedocs.io/en/latest/_modules/collections.html Retrieves an item from the UserDict by key. If the key is not found, it checks for a __missing__ method and raises KeyError if not found. ```python def __getitem__(self, key): if key in self.data: return self.data[key] if hasattr(self.__class__, "__missing__"): return self.__class__.__missing__(self, key) raise KeyError(key) ``` -------------------------------- ### Font Loading and Saving Source: https://ufolib2.readthedocs.io/en/latest/reference.html Methods for instantiating Font objects from paths or readers and saving them to disk. ```APIDOC ## Font.open ### Description Instantiates a new Font object from a path to a UFO. ### Method classmethod ### Parameters #### Path Parameters - **path** (str | bytes | PathLike) - Required - The path to the UFO to load. - **lazy** (bool) - Optional - If True, load glyphs, data files and images as they are accessed. - **validate** (bool) - Optional - If True, enable UFO data model validation during loading. ## Font.save ### Description Saves the font to a specified path. ### Method instance method ### Parameters - **path** (str | bytes | PathLike | None) - Optional - The target path. - **formatVersion** (int) - Optional - The version to save the UFO as (currently only 3). - **structure** (UFOFileStructure) - Optional - Storage structure (None, "zip", or "package"). - **overwrite** (bool) - Optional - If True, overwrites the target path. - **validate** (bool) - Optional - If True, validates data before writing. ``` -------------------------------- ### Partial function application Source: https://ufolib2.readthedocs.io/en/latest/_modules/functools.html Creates a new function with pre-filled arguments and keyword arguments. ```python class partial: """New function with partial application of the given arguments and keywords. """ __slots__ = "func", "args", "keywords", "__dict__", "__weakref__" def __new__(cls, func, /, *args, **keywords): if not callable(func): raise TypeError("the first argument must be callable") if hasattr(func, "func"): args = func.args + args keywords = {**func.keywords, **keywords} func = func.func self = super(partial, cls).__new__(cls) self.func = func self.args = args self.keywords = keywords return self def __call__(self, /, *args, **keywords): keywords = {**self.keywords, **keywords} return self.func(*self.args, *args, **keywords) @recursive_repr() def __repr__(self): qualname = type(self).__qualname__ args = [repr(self.func)] args.extend(repr(x) for x in self.args) args.extend(f"{k}={v!r}" for (k, v) in self.keywords.items()) if type(self).__module__ == "functools": return f"functools.{qualname}({', '.join(args)})" return f"{qualname}({', '.join(args)})" def __reduce__(self): return type(self), (self.func,), (self.func, self.args, self.keywords or None, self.__dict__ or None) def __setstate__(self, state): if not isinstance(state, tuple): raise TypeError("argument to __setstate__ must be a tuple") if len(state) != 4: raise TypeError(f"expected 4 items in state, got {len(state)}") func, args, kwds, namespace = state if (not callable(func) or not isinstance(args, tuple) or (kwds is not None and not isinstance(kwds, dict)) or (namespace is not None and not isinstance(namespace, dict))): raise TypeError("invalid partial state") args = tuple(args) # just in case it's a subclass if kwds is None: kwds = {} elif type(kwds) is not dict: # XXX does it need to be *exactly* dict? kwds = dict(kwds) if namespace is None: namespace = {} self.__dict__ = namespace self.func = func self.args = args self.keywords = kwds __class_getitem__ = classmethod(GenericAlias) try: from _functools import partial except ImportError: pass ``` -------------------------------- ### Glyph Image Management Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/glyph.html Manage the background image reference for a glyph. The `image` property allows getting or setting the image reference. ```APIDOC ## Glyph Image Management ### Description Manages the background image reference for a glyph. The `image` property allows getting or setting the image reference. ### Getter - Returns the `Image` object associated with the glyph. ### Setter - `image` (Image | Mapping[str, Any] | None): Sets the background image reference. Clears it if `None`. Accepts an `Image` object or a mapping containing `fileName` and `transformation` details. ### Request Example ```python from ufoLib2.objects import Image, Transform # Set image using an Image object img_obj = Image(fileName='background.png', transformation=Transform(1, 0, 0, 1, 0, 0)) glyph.image = img_obj # Set image using a mapping img_map = { "fileName": "background.png", "xScale": 1, "xyScale": 0, "yxScale": 0, "yScale": 1, "xOffset": 0, "yOffset": 0 } glyph.image = img_map # Clear image reference glyph.image = None ``` ### Response Example ```json { "image": { "fileName": "background.png", "transformation": { "xScale": 1, "xyScale": 0, "yxScale": 0, "yScale": 1, "xOffset": 0, "yOffset": 0 }, "color": null } } ``` ``` -------------------------------- ### Get List of Glyph Names Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/layer.html Returns a view object containing the names of all glyphs in the layer. This is similar to the keys() method of a dictionary. ```python def keys(self) -> KeysView[str]: """Returns a list of glyph names.""" return self._glyphs.keys() ``` -------------------------------- ### Create New Layer Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/font.html Creates and returns a new Layer object. ```python def newLayer(self, name: str, **kwargs: Any) -> Layer: """Creates and returns a new :class:`.Layer`. Args: name: The name of the new layer. kwargs: The arguments passed to the Layer object constructor. """ return self.layers.newLayer(name, **kwargs) ``` -------------------------------- ### Apply dataclass_transform decorator Source: https://ufolib2.readthedocs.io/en/latest/_modules/typing.html Examples of applying the dataclass_transform decorator to functions, base classes, and metaclasses to enable dataclass-like type checking. ```python @dataclass_transform() def create_model[T](cls: type[T]) -> type[T]: ... return cls @create_model class CustomerModel: id: int name: str ``` ```python @dataclass_transform() class ModelBase: ... class CustomerModel(ModelBase): id: int name: str ``` ```python @dataclass_transform() class ModelMeta(type): ... class ModelBase(metaclass=ModelMeta): ... class CustomerModel(ModelBase): id: int name: str ``` -------------------------------- ### Font.open Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/font.html Instantiates a new Font object from a path to a UFO file. ```APIDOC ## Font.open ### Description Instantiates a new Font object from a path to a UFO. ### Parameters #### Path Parameters - **path** (PathLike) - Required - The path to the UFO to load. #### Query Parameters - **lazy** (bool) - Optional - If True, load glyphs, data files and images as they are accessed. If False, load everything up front. - **validate** (bool) - Optional - If True, enable UFO data model validation during loading. ``` -------------------------------- ### Open Font from Path Source: https://ufolib2.readthedocs.io/en/latest/reference.html Instantiates a new Font object from a path to a UFO. Supports lazy loading and validation. ```python Font.open(_path='path/to/your.ufo', _lazy=True, _validate=True) ``` -------------------------------- ### ImageSet Behavior Source: https://ufolib2.readthedocs.io/en/latest/reference.html Illustrates the dictionary-like behavior of the ImageSet class, including item assignment, retrieval, deletion, and listing items. ```python >>> from ufoLib2 import Font >>> font = Font() >>> # Note: invalid PNG data for demonstration. Use the actual PNG bytes. >>> font.images["test.png"] = b"123" >>> font.images["test2.png"] = b"456" >>> font.images["test.png"] >>> del font.images["test.png"] >>> list(font.images.items()) ``` -------------------------------- ### Get Type Arguments Source: https://ufolib2.readthedocs.io/en/latest/_modules/typing.html Extracts the type arguments from a subscripted type hint, performing necessary substitutions. Simplifies unions as part of the process. ```python def get_args(tp): """Get type arguments with all substitutions performed. For unions, basic simplifications used by Union constructor are performed. Examples:: >>> T = TypeVar('T') >>> assert get_args(Dict[str, int]) == (str, int) >>> assert get_args(int) == () >>> assert get_args(Union[int, Union[T, int], str][int]) == (int, str) >>> assert get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) >>> assert get_args(Callable[[], T][int]) == ([], int) """ if isinstance(tp, _AnnotatedAlias): return (tp.__origin__,) + tp.__metadata__ if isinstance(tp, (_GenericAlias, GenericAlias)): res = tp.__args__ if _should_unflatten_callable_args(tp, res): res = (list(res[:-1]), res[-1]) return res if isinstance(tp, types.UnionType): return tp.__args__ return () ``` -------------------------------- ### Get Origin of a Type Source: https://ufolib2.readthedocs.io/en/latest/_modules/typing.html Retrieves the unsubscripted, generic version of a type. Supports various generic types, unions, and special typing constructs. ```python def get_origin(tp): """Get the unsubscripted version of a type. This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar, Annotated, and others. Return None for unsupported types. Examples:: >>> P = ParamSpec('P') >>> assert get_origin(Literal[42]) is Literal >>> assert get_origin(int) is None >>> assert get_origin(ClassVar[int]) is ClassVar >>> assert get_origin(Generic) is Generic >>> assert get_origin(Generic[T]) is Generic >>> assert get_origin(Union[T, int]) is Union >>> assert get_origin(List[Tuple[T, T]][int]) is list >>> assert get_origin(P.args) is P """ if isinstance(tp, _AnnotatedAlias): return Annotated if isinstance(tp, (_BaseGenericAlias, GenericAlias, ParamSpecArgs, ParamSpecKwargs)): return tp.__origin__ if tp is Generic: return Generic if isinstance(tp, types.UnionType): return types.UnionType return None ``` -------------------------------- ### Converting namedtuple to Dictionary and Back Source: https://ufolib2.readthedocs.io/en/latest/_modules/collections.html Shows how to convert a namedtuple instance to a dictionary using _asdict() and create a new instance from a dictionary using the class constructor. Useful for serialization or data manipulation. ```python >>> d = p._asdict() # convert to a dictionary >>> d['x'] 11 >>> Point(**d) # convert from a dictionary Point(x=11, y=22) ``` -------------------------------- ### LayerSet Class Overview Source: https://ufolib2.readthedocs.io/en/latest/reference.html Provides an overview of the LayerSet class, its behavior, and basic operations. ```APIDOC ## LayerSet Class ### Description Represents a mapping of layer names to Layer objects. It behaves partly like a dictionary `Dict[str, Layer]`, with layer creation and loading handled by specific methods. By default, layers and their glyphs are loaded lazily. ### Basic Operations To get the number of layers: ```python layerCount = len(font.layers) ``` To iterate over all layers: ```python for layer in font.layers: ... ``` To check if a specific layer exists: ```python exists = "myLayerName" in font.layers ``` To get a specific layer: ```python font.layers["myLayerName"] ``` To delete a specific layer: ```python del font.layers["myLayerName"] ``` ``` -------------------------------- ### Get Layer Safely Source: https://ufolib2.readthedocs.io/en/latest/_modules/ufoLib2/objects/layerSet.html Retrieves a layer by name, returning a default value if the layer is not found. This is a safer alternative to direct dictionary access. ```python def get(self, name: str, default: T | None = None) -> T | Layer | None: try: return self[name] except KeyError: return default ``` -------------------------------- ### OrderedDict Class Overview Source: https://ufolib2.readthedocs.io/en/latest/_modules/collections.html Provides an overview of the OrderedDict class and its core functionalities. ```APIDOC ## OrderedDict Dictionary that remembers insertion order. An inherited dict maps keys to values. The inherited dict provides __getitem__, __len__, __contains__, and get. The remaining methods are order-aware. Big-O running times for all methods are the same as regular dictionaries. The internal self.__map dict maps keys to links in a doubly linked list. The circular doubly linked list starts and ends with a sentinel element. The sentinel element never gets deleted (this simplifies the algorithm). The sentinel is in self.__hardroot with a weakref proxy in self.__root. The prev links are weakref proxies (to prevent circular references). Individual links are kept alive by the hard reference in self.__map. Those hard references disappear when a key is deleted from an OrderedDict. ``` -------------------------------- ### Get Layer Keys (Glyph Names) Source: https://ufolib2.readthedocs.io/en/latest/reference.html Retrieve a view object containing the names of all glyphs in the layer using the keys() method. This is similar to dict.keys(). ```python layer.keys() ```