Coverage for src/python/ensembl/vep/parsers/parser.py: 98%
41 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
1# See the NOTICE file distributed with this work for additional information
2# regarding copyright ownership.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Parser interface."""
16from __future__ import annotations
18from abc import ABC, abstractmethod
19from pathlib import Path
20from typing import Generic, Self, TypeVar
21from attrs import define
23T = TypeVar("T")
26@define(kw_only=True, auto_attribs=True)
27class Parser(ABC, Generic[T]):
28 """Parser interface.
30 Attributes:
31 format (str): The format of the file being parsed.
32 metadata (dict): A dictionary containing metadata about the file being parsed.
33 """
35 format: str
37 @property
38 def metadata(self) -> dict:
39 """Return parsed file metadata.
41 Returns:
42 dict: The metadata dictionary.
43 """
45 return self._metadata
47 @property
48 def _metadata(self) -> dict:
49 """Metadata dictionary.
51 Returns:
52 dict: The metadata dictionary.
53 """
55 return {}
57 @property
58 def index_sequence_names(self) -> list[str]:
59 """Return reference sequence names declared by the index.
61 Returns:
62 list[str]: The reference sequence names, or an empty list when the parser has no
63 index or does not expose this information.
64 """
66 return []
68 @abstractmethod
69 def open(self, file_path: str, mode: str) -> Parser:
70 """Open a file for parsing.
72 Args:
73 file_path (str): The path to the file to be parsed.
74 mode (str): The mode in which to open the file.
76 Returns:
77 Parser: The parser instance.
78 """
80 raise NotImplementedError
82 @abstractmethod
83 def close(self) -> None:
84 """Close the parser."""
86 raise NotImplementedError
88 @abstractmethod
89 def seek(
90 self,
91 region: str | None = None,
92 *,
93 seq_region_name: str | None = None,
94 start: int | None = None,
95 end: int | None = None,
96 ) -> bool:
97 """Seek to a region and make next() stream matching raw rows.
99 Args:
100 region (str | None): The region to seek to, in the format "chr:start-end".
101 seq_region_name (str | None): The name of the region to seek to.
102 start (int | None): The start position of the region to seek to.
103 end (int | None): The end position of the region to seek to.
105 Returns:
106 bool: True if the seek was successful, False otherwise.
107 """
109 raise NotImplementedError
111 @abstractmethod
112 def next(self) -> T | None:
113 """Return the next raw row from the active region query.
115 Returns:
116 T | None: The next raw row, or None if there are no more rows.
117 """
119 raise NotImplementedError
121 def records(self, limit: int | None = None) -> list[T]:
122 """Return all records from the active region query.
124 Args:
125 limit (int | None): The maximum number of records to return. If None, return all records.
127 Returns:
128 list[T]: A list of records from the active region query.
129 """
131 records: list[T] = []
132 while limit is None or len(records) < limit:
133 record = self.next()
134 if record is None:
135 break
136 records.append(record)
137 return records
139 def __iter__(self) -> Parser:
140 return self
142 def __next__(self) -> T:
143 record = self.next()
145 if record is None:
146 raise StopIteration
148 return record
150 def __enter__(self) -> Self:
151 return self
153 def __exit__(self, *exc_info: object) -> None:
154 self.close()
156 @staticmethod
157 def parse_text(data: str, limit: int | None = None) -> list[T]:
158 """Parse raw text data and return a list of records.
160 Args:
161 data (str): The raw text data to parse.
162 limit (int | None): The maximum number of records to return. If None, return all records.
164 Returns:
165 list[T]: A list of records parsed from the raw text data.
166 """
168 raise NotImplementedError
170 @staticmethod
171 def parse_file(file_path: str | Path, limit: int | None = None) -> list[T]:
172 """Parse a file and return a list of records.
174 Args:
175 file_path (str | Path): The path to the file to parse.
176 limit (int | None): The maximum number of records to return. If None, return all records.
178 Returns:
179 list[T]: A list of records parsed from the file.
180 """
182 raise NotImplementedError