Source code for ensembl.vep.parsers.parser

# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Parser interface."""

from __future__ import annotations

from abc import ABC, abstractmethod
from pathlib import Path
from typing import Generic, Self, TypeVar
from attrs import define

T = TypeVar("T")


[docs] @define(kw_only=True, auto_attribs=True) class Parser(ABC, Generic[T]): """Parser interface. Attributes: format (str): The format of the file being parsed. metadata (dict): A dictionary containing metadata about the file being parsed. """ format: str @property def metadata(self) -> dict: """Return parsed file metadata. Returns: dict: The metadata dictionary. """ return self._metadata @property def _metadata(self) -> dict: """Metadata dictionary. Returns: dict: The metadata dictionary. """ return {} @property def index_sequence_names(self) -> list[str]: """Return reference sequence names declared by the index. Returns: list[str]: The reference sequence names, or an empty list when the parser has no index or does not expose this information. """ return []
[docs] @abstractmethod def open(self, file_path: str, mode: str) -> Parser: """Open a file for parsing. Args: file_path (str): The path to the file to be parsed. mode (str): The mode in which to open the file. Returns: Parser: The parser instance. """ raise NotImplementedError
[docs] @abstractmethod def close(self) -> None: """Close the parser.""" raise NotImplementedError
[docs] @abstractmethod def seek( self, region: str | None = None, *, seq_region_name: str | None = None, start: int | None = None, end: int | None = None, ) -> bool: """Seek to a region and make next() stream matching raw rows. Args: region (str | None): The region to seek to, in the format "chr:start-end". seq_region_name (str | None): The name of the region to seek to. start (int | None): The start position of the region to seek to. end (int | None): The end position of the region to seek to. Returns: bool: True if the seek was successful, False otherwise. """ raise NotImplementedError
[docs] @abstractmethod def next(self) -> T | None: """Return the next raw row from the active region query. Returns: T | None: The next raw row, or None if there are no more rows. """ raise NotImplementedError
[docs] def records(self, limit: int | None = None) -> list[T]: """Return all records from the active region query. Args: limit (int | None): The maximum number of records to return. If None, return all records. Returns: list[T]: A list of records from the active region query. """ records: list[T] = [] while limit is None or len(records) < limit: record = self.next() if record is None: break records.append(record) return records
def __iter__(self) -> Parser: return self def __next__(self) -> T: record = self.next() if record is None: raise StopIteration return record def __enter__(self) -> Self: return self def __exit__(self, *exc_info: object) -> None: self.close()
[docs] @staticmethod def parse_text(data: str, limit: int | None = None) -> list[T]: """Parse raw text data and return a list of records. Args: data (str): The raw text data to parse. limit (int | None): The maximum number of records to return. If None, return all records. Returns: list[T]: A list of records parsed from the raw text data. """ raise NotImplementedError
[docs] @staticmethod def parse_file(file_path: str | Path, limit: int | None = None) -> list[T]: """Parse a file and return a list of records. Args: file_path (str | Path): The path to the file to parse. limit (int | None): The maximum number of records to return. If None, return all records. Returns: list[T]: A list of records parsed from the file. """ raise NotImplementedError