sqlglot.helper
1from __future__ import annotations 2 3import datetime 4import inspect 5import logging 6import re 7import sys 8import typing as t 9from collections.abc import Collection, Set, Iterable, Sequence, Iterator, Mapping 10from copy import copy 11from decimal import Decimal, InvalidOperation 12from difflib import get_close_matches 13from enum import Enum 14from itertools import count 15from builtins import type as Type 16 17try: 18 from mypy_extensions import mypyc_attr, trait, i64 19except ImportError: 20 21 def mypyc_attr(*attrs: str, **kwattrs: object) -> t.Callable[[t.Any], t.Any]: # type: ignore[misc] 22 return lambda f: f 23 24 def trait(f: t.Any) -> t.Any: # type: ignore[misc] 25 return f 26 27 i64 = int # type: ignore[misc,assignment] 28 29 30T = t.TypeVar("T") 31E = t.TypeVar("E") 32 33if t.TYPE_CHECKING: 34 from sqlglot.expressions import Expr 35 36 37CAMEL_CASE_PATTERN = re.compile("(?<!^)(?=[A-Z])") 38PYTHON_VERSION = sys.version_info[:2] 39logger = logging.getLogger("sqlglot") 40 41 42class AutoName(Enum): 43 """ 44 This is used for creating Enum classes where `auto()` is the string form 45 of the corresponding enum's identifier (e.g. FOO.value results in "FOO"). 46 47 Reference: https://docs.python.org/3/howto/enum.html#using-automatic-values 48 """ 49 50 def _generate_next_value_(name, _start, _count, _last_values): 51 return name 52 53 54def suggest_closest_match_and_fail( 55 kind: str, 56 word: str, 57 possibilities: Iterable[str], 58) -> None: 59 close_matches = get_close_matches(word, possibilities, n=1) 60 61 similar = seq_get(close_matches, 0) or "" 62 if similar: 63 similar = f" Did you mean {similar}?" 64 65 raise ValueError(f"Unknown {kind} '{word}'.{similar}") 66 67 68def seq_get(seq: Sequence[T], index: int) -> T | None: 69 """Returns the value in `seq` at position `index`, or `None` if `index` is out of bounds.""" 70 try: 71 return seq[index] 72 except IndexError: 73 return None 74 75 76def ensure_list(value: T | list[T] | tuple[T, ...] | None) -> list[T]: 77 """ 78 Ensures that a value is a list, otherwise casts or wraps it into one. 79 80 Args: 81 value: The value of interest. 82 83 Returns: 84 The value cast as a list if it's a list or a tuple, or else the value wrapped in a list. 85 """ 86 if value is None: 87 return [] 88 if isinstance(value, list): 89 return value 90 if isinstance(value, tuple): 91 return list(value) 92 93 return [value] 94 95 96@t.overload 97def ensure_collection(value: Collection[T]) -> Collection[T]: ... 98 99 100@t.overload 101def ensure_collection(value: T) -> Collection[T]: ... 102 103 104def ensure_collection(value): 105 """ 106 Ensures that a value is a collection (excluding `str` and `bytes`), otherwise wraps it into a list. 107 108 Args: 109 value: The value of interest. 110 111 Returns: 112 The value if it's a collection, or else the value wrapped in a list. 113 """ 114 if value is None: 115 return [] 116 return ( 117 value if isinstance(value, Collection) and not isinstance(value, (str, bytes)) else [value] 118 ) 119 120 121def csv(*args: str, sep: str = ", ") -> str: 122 """ 123 Formats any number of string arguments as CSV. 124 125 Args: 126 args: The string arguments to format. 127 sep: The argument separator. 128 129 Returns: 130 The arguments formatted as a CSV string. 131 """ 132 return sep.join(arg for arg in args if arg) 133 134 135def subclasses( 136 module_name: str, 137 classes: Type[T] | tuple[Type[T], ...], 138 exclude: set[Type[T]] = set(), 139) -> list[Type[T]]: 140 """ 141 Returns all subclasses for a collection of classes, possibly excluding some of them. 142 143 Args: 144 module_name: The name of the module to search for subclasses in. 145 classes: Class(es) we want to find the subclasses of. 146 exclude: Classes we want to exclude from the returned list. 147 148 Returns: 149 The target subclasses. 150 """ 151 return [ 152 obj 153 for _, obj in inspect.getmembers( 154 sys.modules[module_name], 155 lambda obj: inspect.isclass(obj) and issubclass(obj, classes) and obj not in exclude, 156 ) 157 ] 158 159 160def camel_to_snake_case(name: str) -> str: 161 """Converts `name` from camelCase to snake_case and returns the result.""" 162 return CAMEL_CASE_PATTERN.sub("_", name).upper() 163 164 165def decode_unicode_escapes(text: str, escape: str, *, strict: bool = False) -> str: 166 """Decode SQL Unicode escapes, including doubled escape characters and UTF-16 pairs.""" 167 prefix = re.escape(escape) 168 pattern = rf"{prefix}(?:\+([0-9a-fA-F]{{6}})|([0-9a-fA-F]{{4}})|({prefix}))" 169 if strict: 170 pattern += "?" # Also match a bare escape so that decode can reject it. 171 172 def decode(match: re.Match[str]) -> str: 173 digits = match[1] or match[2] 174 if digits: 175 return chr(int(digits, 16)) 176 if strict and match[3] is None: 177 raise ValueError("Invalid Unicode escape") 178 return escape 179 180 return re.sub(pattern, decode, text).encode("utf-16", "surrogatepass").decode("utf-16") 181 182 183def while_changing(expression: E, func: t.Callable[[E], E]) -> E: 184 """ 185 Applies a transformation to a given expression until a fix point is reached. 186 187 Args: 188 expression: The expression to be transformed. 189 func: The transformation to be applied. 190 191 Returns: 192 The transformed expression. 193 """ 194 195 while True: 196 start_hash = hash(expression) 197 expression = func(expression) 198 end_hash = hash(expression) 199 200 if start_hash == end_hash: 201 break 202 203 return expression 204 205 206def tsort(dag: dict[T, set[T]]) -> list[T]: 207 """ 208 Sorts a given directed acyclic graph in topological order. 209 210 Args: 211 dag: The graph to be sorted. 212 213 Returns: 214 A list that contains all of the graph's nodes in topological order. 215 """ 216 result = [] 217 218 for node, deps in tuple(dag.items()): 219 for dep in deps: 220 if dep not in dag: 221 dag[dep] = set() 222 223 while dag: 224 current = {node for node, deps in dag.items() if not deps} 225 226 if not current: 227 raise ValueError("Cycle error") 228 229 for node in current: 230 dag.pop(node) 231 232 for deps in dag.values(): 233 deps -= current 234 235 result.extend(sorted(current)) # type: ignore 236 237 return result 238 239 240def find_new_name(taken: Collection[str], base: str) -> str: 241 """ 242 Searches for a new name. 243 244 Args: 245 taken: A collection of taken names. 246 base: Base name to alter. 247 248 Returns: 249 The new, available name. 250 """ 251 if base not in taken: 252 return base 253 254 i = 2 255 new = f"{base}_{i}" 256 while new in taken: 257 i += 1 258 new = f"{base}_{i}" 259 260 return new 261 262 263def is_int(text: str) -> bool: 264 return is_type(text, int) 265 266 267def to_int(value: str | int | Decimal, max_digits: int = 4300) -> int | None: 268 """Unlike int(), never materializes a huge int from a short exponent like 1e1000000.""" 269 try: 270 number = Decimal(value) 271 except InvalidOperation: 272 return None 273 274 if ( 275 not number.is_finite() 276 or number.adjusted() >= max_digits 277 or number != number.to_integral_value() 278 ): 279 return None 280 return int(number) 281 282 283def is_float(text: str) -> bool: 284 return is_type(text, float) 285 286 287def is_type(text: str, target_type: Type) -> bool: 288 try: 289 target_type(text) 290 return True 291 except ValueError: 292 return False 293 294 295def name_sequence(prefix: str) -> t.Callable[[], str]: 296 """Returns a name generator given a prefix (e.g. a0, a1, a2, ... if the prefix is "a").""" 297 sequence = count() 298 return lambda: f"{prefix}{next(sequence)}" 299 300 301def object_to_dict(obj: t.Any, **kwargs) -> dict: 302 """Returns a dictionary created from an object's attributes.""" 303 return { 304 **{k: v.copy() if hasattr(v, "copy") else copy(v) for k, v in vars(obj).items()}, 305 **kwargs, 306 } 307 308 309def split_num_words( 310 value: str, sep: str, min_num_words: int, fill_from_start: bool = True 311) -> list[str | None]: 312 """ 313 Perform a split on a value and return N words as a result with `None` used for words that don't exist. 314 315 Args: 316 value: The value to be split. 317 sep: The value to use to split on. 318 min_num_words: The minimum number of words that are going to be in the result. 319 fill_from_start: Indicates that if `None` values should be inserted at the start or end of the list. 320 321 Examples: 322 >>> split_num_words("db.table", ".", 3) 323 [None, 'db', 'table'] 324 >>> split_num_words("db.table", ".", 3, fill_from_start=False) 325 ['db', 'table', None] 326 >>> split_num_words("db.table", ".", 1) 327 ['db', 'table'] 328 329 Returns: 330 The list of words returned by `split`, possibly augmented by a number of `None` values. 331 """ 332 words = value.split(sep) 333 if fill_from_start: 334 return [None] * (min_num_words - len(words)) + words 335 return words + [None] * (min_num_words - len(words)) 336 337 338def is_iterable(value: t.Any) -> bool: 339 """ 340 Checks if the value is an iterable, excluding the types `str` and `bytes`. 341 342 Examples: 343 >>> is_iterable([1,2]) 344 True 345 >>> is_iterable("test") 346 False 347 348 Args: 349 value: The value to check if it is an iterable. 350 351 Returns: 352 A `bool` value indicating if it is an iterable. 353 """ 354 from sqlglot.expressions import Expr 355 356 return hasattr(value, "__iter__") and not isinstance(value, (str, bytes, Expr)) 357 358 359def flatten(values: Iterable[Iterable[t.Any] | t.Any]) -> Iterator[t.Any]: 360 """ 361 Flattens an iterable that can contain both iterable and non-iterable elements. Objects of 362 type `str` and `bytes` are not regarded as iterables. 363 364 Examples: 365 >>> list(flatten([[1, 2], 3, {4}, (5, "bla")])) 366 [1, 2, 3, 4, 5, 'bla'] 367 >>> list(flatten([1, 2, 3])) 368 [1, 2, 3] 369 370 Args: 371 values: The value to be flattened. 372 373 Yields: 374 Non-iterable elements in `values`. 375 """ 376 for value in values: 377 if is_iterable(value): 378 yield from flatten(value) 379 else: 380 yield value 381 382 383def dict_depth(d: t.Any) -> int: 384 """ 385 Get the nesting depth of a dictionary. 386 387 Example: 388 >>> dict_depth(None) 389 0 390 >>> dict_depth({}) 391 1 392 >>> dict_depth({"a": "b"}) 393 1 394 >>> dict_depth({"a": {}}) 395 2 396 >>> dict_depth({"a": {"b": {}}}) 397 3 398 """ 399 try: 400 return 1 + dict_depth(next(iter(d.values()))) 401 except AttributeError: 402 # d doesn't have attribute "values" 403 return 0 404 except StopIteration: 405 # d.values() returns an empty sequence 406 return 1 407 408 409def first(it: Iterable[T]) -> T: 410 """Returns the first element from an iterable (useful for sets).""" 411 return next(i for i in it) 412 413 414@t.overload 415def to_bool(value: None) -> None: ... 416 417 418@t.overload 419def to_bool(value: bool) -> bool: ... 420 421 422@t.overload 423def to_bool(value: str) -> str | bool: ... 424 425 426def to_bool(value: str | bool | None) -> str | bool | None: 427 if isinstance(value, bool) or value is None: 428 return value 429 430 # Coerce the value to boolean if it matches to the truthy/falsy values below 431 value_lower = value.lower() 432 if value_lower in ("true", "1"): 433 return True 434 if value_lower in ("false", "0"): 435 return False 436 437 return value 438 439 440def merge_ranges(ranges: list[tuple[t.Any, t.Any]]) -> list[tuple[t.Any, t.Any]]: 441 """ 442 Merges a sequence of ranges, represented as tuples (low, high) whose values 443 belong to some totally-ordered set. 444 445 Example: 446 >>> merge_ranges([(1, 3), (2, 6)]) 447 [(1, 6)] 448 """ 449 if not ranges: 450 return [] 451 452 ranges = sorted(ranges) 453 454 merged = [ranges[0]] 455 456 for start, end in ranges[1:]: 457 last_start, last_end = merged[-1] 458 459 if start <= last_end: 460 merged[-1] = (last_start, max(last_end, end)) 461 else: 462 merged.append((start, end)) 463 464 return merged 465 466 467def is_iso_date(text: str) -> bool: 468 try: 469 datetime.date.fromisoformat(text) 470 return True 471 except ValueError: 472 return False 473 474 475def is_iso_datetime(text: str) -> bool: 476 try: 477 datetime.datetime.fromisoformat(text) 478 return True 479 except ValueError: 480 return False 481 482 483# Interval units that operate on date components 484DATE_UNITS = {"day", "week", "month", "quarter", "year", "year_month"} 485 486 487def is_date_unit(expression: Expr | None) -> bool: 488 return expression is not None and expression.name.lower() in DATE_UNITS 489 490 491K = t.TypeVar("K") 492V = t.TypeVar("V") 493 494 495class SingleValuedMapping(Mapping[K, V]): 496 """ 497 Mapping where all keys return the same value. 498 499 This rigamarole is meant to avoid copying keys, which was originally intended 500 as an optimization while qualifying columns for tables with lots of columns. 501 """ 502 503 def __init__(self, keys: Collection[K], value: V): 504 self._keys = keys if isinstance(keys, Set) else set(keys) 505 self._value = value 506 507 def __getitem__(self, key: K) -> V: 508 if key in self._keys: 509 return self._value 510 raise KeyError(key) 511 512 def __len__(self) -> int: 513 return len(self._keys) 514 515 def __iter__(self) -> Iterator[K]: 516 return iter(self._keys)
43class AutoName(Enum): 44 """ 45 This is used for creating Enum classes where `auto()` is the string form 46 of the corresponding enum's identifier (e.g. FOO.value results in "FOO"). 47 48 Reference: https://docs.python.org/3/howto/enum.html#using-automatic-values 49 """ 50 51 def _generate_next_value_(name, _start, _count, _last_values): 52 return name
This is used for creating Enum classes where auto() is the string form
of the corresponding enum's identifier (e.g. FOO.value results in "FOO").
Reference: https://docs.python.org/3/howto/enum.html#using-automatic-values
55def suggest_closest_match_and_fail( 56 kind: str, 57 word: str, 58 possibilities: Iterable[str], 59) -> None: 60 close_matches = get_close_matches(word, possibilities, n=1) 61 62 similar = seq_get(close_matches, 0) or "" 63 if similar: 64 similar = f" Did you mean {similar}?" 65 66 raise ValueError(f"Unknown {kind} '{word}'.{similar}")
69def seq_get(seq: Sequence[T], index: int) -> T | None: 70 """Returns the value in `seq` at position `index`, or `None` if `index` is out of bounds.""" 71 try: 72 return seq[index] 73 except IndexError: 74 return None
Returns the value in seq at position index, or None if index is out of bounds.
77def ensure_list(value: T | list[T] | tuple[T, ...] | None) -> list[T]: 78 """ 79 Ensures that a value is a list, otherwise casts or wraps it into one. 80 81 Args: 82 value: The value of interest. 83 84 Returns: 85 The value cast as a list if it's a list or a tuple, or else the value wrapped in a list. 86 """ 87 if value is None: 88 return [] 89 if isinstance(value, list): 90 return value 91 if isinstance(value, tuple): 92 return list(value) 93 94 return [value]
Ensures that a value is a list, otherwise casts or wraps it into one.
Arguments:
- value: The value of interest.
Returns:
The value cast as a list if it's a list or a tuple, or else the value wrapped in a list.
105def ensure_collection(value): 106 """ 107 Ensures that a value is a collection (excluding `str` and `bytes`), otherwise wraps it into a list. 108 109 Args: 110 value: The value of interest. 111 112 Returns: 113 The value if it's a collection, or else the value wrapped in a list. 114 """ 115 if value is None: 116 return [] 117 return ( 118 value if isinstance(value, Collection) and not isinstance(value, (str, bytes)) else [value] 119 )
Ensures that a value is a collection (excluding str and bytes), otherwise wraps it into a list.
Arguments:
- value: The value of interest.
Returns:
The value if it's a collection, or else the value wrapped in a list.
122def csv(*args: str, sep: str = ", ") -> str: 123 """ 124 Formats any number of string arguments as CSV. 125 126 Args: 127 args: The string arguments to format. 128 sep: The argument separator. 129 130 Returns: 131 The arguments formatted as a CSV string. 132 """ 133 return sep.join(arg for arg in args if arg)
Formats any number of string arguments as CSV.
Arguments:
- args: The string arguments to format.
- sep: The argument separator.
Returns:
The arguments formatted as a CSV string.
136def subclasses( 137 module_name: str, 138 classes: Type[T] | tuple[Type[T], ...], 139 exclude: set[Type[T]] = set(), 140) -> list[Type[T]]: 141 """ 142 Returns all subclasses for a collection of classes, possibly excluding some of them. 143 144 Args: 145 module_name: The name of the module to search for subclasses in. 146 classes: Class(es) we want to find the subclasses of. 147 exclude: Classes we want to exclude from the returned list. 148 149 Returns: 150 The target subclasses. 151 """ 152 return [ 153 obj 154 for _, obj in inspect.getmembers( 155 sys.modules[module_name], 156 lambda obj: inspect.isclass(obj) and issubclass(obj, classes) and obj not in exclude, 157 ) 158 ]
Returns all subclasses for a collection of classes, possibly excluding some of them.
Arguments:
- module_name: The name of the module to search for subclasses in.
- classes: Class(es) we want to find the subclasses of.
- exclude: Classes we want to exclude from the returned list.
Returns:
The target subclasses.
161def camel_to_snake_case(name: str) -> str: 162 """Converts `name` from camelCase to snake_case and returns the result.""" 163 return CAMEL_CASE_PATTERN.sub("_", name).upper()
Converts name from camelCase to snake_case and returns the result.
166def decode_unicode_escapes(text: str, escape: str, *, strict: bool = False) -> str: 167 """Decode SQL Unicode escapes, including doubled escape characters and UTF-16 pairs.""" 168 prefix = re.escape(escape) 169 pattern = rf"{prefix}(?:\+([0-9a-fA-F]{{6}})|([0-9a-fA-F]{{4}})|({prefix}))" 170 if strict: 171 pattern += "?" # Also match a bare escape so that decode can reject it. 172 173 def decode(match: re.Match[str]) -> str: 174 digits = match[1] or match[2] 175 if digits: 176 return chr(int(digits, 16)) 177 if strict and match[3] is None: 178 raise ValueError("Invalid Unicode escape") 179 return escape 180 181 return re.sub(pattern, decode, text).encode("utf-16", "surrogatepass").decode("utf-16")
Decode SQL Unicode escapes, including doubled escape characters and UTF-16 pairs.
184def while_changing(expression: E, func: t.Callable[[E], E]) -> E: 185 """ 186 Applies a transformation to a given expression until a fix point is reached. 187 188 Args: 189 expression: The expression to be transformed. 190 func: The transformation to be applied. 191 192 Returns: 193 The transformed expression. 194 """ 195 196 while True: 197 start_hash = hash(expression) 198 expression = func(expression) 199 end_hash = hash(expression) 200 201 if start_hash == end_hash: 202 break 203 204 return expression
Applies a transformation to a given expression until a fix point is reached.
Arguments:
- expression: The expression to be transformed.
- func: The transformation to be applied.
Returns:
The transformed expression.
207def tsort(dag: dict[T, set[T]]) -> list[T]: 208 """ 209 Sorts a given directed acyclic graph in topological order. 210 211 Args: 212 dag: The graph to be sorted. 213 214 Returns: 215 A list that contains all of the graph's nodes in topological order. 216 """ 217 result = [] 218 219 for node, deps in tuple(dag.items()): 220 for dep in deps: 221 if dep not in dag: 222 dag[dep] = set() 223 224 while dag: 225 current = {node for node, deps in dag.items() if not deps} 226 227 if not current: 228 raise ValueError("Cycle error") 229 230 for node in current: 231 dag.pop(node) 232 233 for deps in dag.values(): 234 deps -= current 235 236 result.extend(sorted(current)) # type: ignore 237 238 return result
Sorts a given directed acyclic graph in topological order.
Arguments:
- dag: The graph to be sorted.
Returns:
A list that contains all of the graph's nodes in topological order.
241def find_new_name(taken: Collection[str], base: str) -> str: 242 """ 243 Searches for a new name. 244 245 Args: 246 taken: A collection of taken names. 247 base: Base name to alter. 248 249 Returns: 250 The new, available name. 251 """ 252 if base not in taken: 253 return base 254 255 i = 2 256 new = f"{base}_{i}" 257 while new in taken: 258 i += 1 259 new = f"{base}_{i}" 260 261 return new
Searches for a new name.
Arguments:
- taken: A collection of taken names.
- base: Base name to alter.
Returns:
The new, available name.
268def to_int(value: str | int | Decimal, max_digits: int = 4300) -> int | None: 269 """Unlike int(), never materializes a huge int from a short exponent like 1e1000000.""" 270 try: 271 number = Decimal(value) 272 except InvalidOperation: 273 return None 274 275 if ( 276 not number.is_finite() 277 or number.adjusted() >= max_digits 278 or number != number.to_integral_value() 279 ): 280 return None 281 return int(number)
Unlike int(), never materializes a huge int from a short exponent like 1e1000000.
296def name_sequence(prefix: str) -> t.Callable[[], str]: 297 """Returns a name generator given a prefix (e.g. a0, a1, a2, ... if the prefix is "a").""" 298 sequence = count() 299 return lambda: f"{prefix}{next(sequence)}"
Returns a name generator given a prefix (e.g. a0, a1, a2, ... if the prefix is "a").
302def object_to_dict(obj: t.Any, **kwargs) -> dict: 303 """Returns a dictionary created from an object's attributes.""" 304 return { 305 **{k: v.copy() if hasattr(v, "copy") else copy(v) for k, v in vars(obj).items()}, 306 **kwargs, 307 }
Returns a dictionary created from an object's attributes.
310def split_num_words( 311 value: str, sep: str, min_num_words: int, fill_from_start: bool = True 312) -> list[str | None]: 313 """ 314 Perform a split on a value and return N words as a result with `None` used for words that don't exist. 315 316 Args: 317 value: The value to be split. 318 sep: The value to use to split on. 319 min_num_words: The minimum number of words that are going to be in the result. 320 fill_from_start: Indicates that if `None` values should be inserted at the start or end of the list. 321 322 Examples: 323 >>> split_num_words("db.table", ".", 3) 324 [None, 'db', 'table'] 325 >>> split_num_words("db.table", ".", 3, fill_from_start=False) 326 ['db', 'table', None] 327 >>> split_num_words("db.table", ".", 1) 328 ['db', 'table'] 329 330 Returns: 331 The list of words returned by `split`, possibly augmented by a number of `None` values. 332 """ 333 words = value.split(sep) 334 if fill_from_start: 335 return [None] * (min_num_words - len(words)) + words 336 return words + [None] * (min_num_words - len(words))
Perform a split on a value and return N words as a result with None used for words that don't exist.
Arguments:
- value: The value to be split.
- sep: The value to use to split on.
- min_num_words: The minimum number of words that are going to be in the result.
- fill_from_start: Indicates that if
Nonevalues should be inserted at the start or end of the list.
Examples:
>>> split_num_words("db.table", ".", 3) [None, 'db', 'table'] >>> split_num_words("db.table", ".", 3, fill_from_start=False) ['db', 'table', None] >>> split_num_words("db.table", ".", 1) ['db', 'table']
Returns:
The list of words returned by
split, possibly augmented by a number ofNonevalues.
339def is_iterable(value: t.Any) -> bool: 340 """ 341 Checks if the value is an iterable, excluding the types `str` and `bytes`. 342 343 Examples: 344 >>> is_iterable([1,2]) 345 True 346 >>> is_iterable("test") 347 False 348 349 Args: 350 value: The value to check if it is an iterable. 351 352 Returns: 353 A `bool` value indicating if it is an iterable. 354 """ 355 from sqlglot.expressions import Expr 356 357 return hasattr(value, "__iter__") and not isinstance(value, (str, bytes, Expr))
Checks if the value is an iterable, excluding the types str and bytes.
Examples:
>>> is_iterable([1,2]) True >>> is_iterable("test") False
Arguments:
- value: The value to check if it is an iterable.
Returns:
A
boolvalue indicating if it is an iterable.
360def flatten(values: Iterable[Iterable[t.Any] | t.Any]) -> Iterator[t.Any]: 361 """ 362 Flattens an iterable that can contain both iterable and non-iterable elements. Objects of 363 type `str` and `bytes` are not regarded as iterables. 364 365 Examples: 366 >>> list(flatten([[1, 2], 3, {4}, (5, "bla")])) 367 [1, 2, 3, 4, 5, 'bla'] 368 >>> list(flatten([1, 2, 3])) 369 [1, 2, 3] 370 371 Args: 372 values: The value to be flattened. 373 374 Yields: 375 Non-iterable elements in `values`. 376 """ 377 for value in values: 378 if is_iterable(value): 379 yield from flatten(value) 380 else: 381 yield value
Flattens an iterable that can contain both iterable and non-iterable elements. Objects of
type str and bytes are not regarded as iterables.
Examples:
>>> list(flatten([[1, 2], 3, {4}, (5, "bla")])) [1, 2, 3, 4, 5, 'bla'] >>> list(flatten([1, 2, 3])) [1, 2, 3]
Arguments:
- values: The value to be flattened.
Yields:
Non-iterable elements in
values.
384def dict_depth(d: t.Any) -> int: 385 """ 386 Get the nesting depth of a dictionary. 387 388 Example: 389 >>> dict_depth(None) 390 0 391 >>> dict_depth({}) 392 1 393 >>> dict_depth({"a": "b"}) 394 1 395 >>> dict_depth({"a": {}}) 396 2 397 >>> dict_depth({"a": {"b": {}}}) 398 3 399 """ 400 try: 401 return 1 + dict_depth(next(iter(d.values()))) 402 except AttributeError: 403 # d doesn't have attribute "values" 404 return 0 405 except StopIteration: 406 # d.values() returns an empty sequence 407 return 1
Get the nesting depth of a dictionary.
Example:
>>> dict_depth(None) 0 >>> dict_depth({}) 1 >>> dict_depth({"a": "b"}) 1 >>> dict_depth({"a": {}}) 2 >>> dict_depth({"a": {"b": {}}}) 3
410def first(it: Iterable[T]) -> T: 411 """Returns the first element from an iterable (useful for sets).""" 412 return next(i for i in it)
Returns the first element from an iterable (useful for sets).
427def to_bool(value: str | bool | None) -> str | bool | None: 428 if isinstance(value, bool) or value is None: 429 return value 430 431 # Coerce the value to boolean if it matches to the truthy/falsy values below 432 value_lower = value.lower() 433 if value_lower in ("true", "1"): 434 return True 435 if value_lower in ("false", "0"): 436 return False 437 438 return value
441def merge_ranges(ranges: list[tuple[t.Any, t.Any]]) -> list[tuple[t.Any, t.Any]]: 442 """ 443 Merges a sequence of ranges, represented as tuples (low, high) whose values 444 belong to some totally-ordered set. 445 446 Example: 447 >>> merge_ranges([(1, 3), (2, 6)]) 448 [(1, 6)] 449 """ 450 if not ranges: 451 return [] 452 453 ranges = sorted(ranges) 454 455 merged = [ranges[0]] 456 457 for start, end in ranges[1:]: 458 last_start, last_end = merged[-1] 459 460 if start <= last_end: 461 merged[-1] = (last_start, max(last_end, end)) 462 else: 463 merged.append((start, end)) 464 465 return merged
Merges a sequence of ranges, represented as tuples (low, high) whose values belong to some totally-ordered set.
Example:
>>> merge_ranges([(1, 3), (2, 6)]) [(1, 6)]
496class SingleValuedMapping(Mapping[K, V]): 497 """ 498 Mapping where all keys return the same value. 499 500 This rigamarole is meant to avoid copying keys, which was originally intended 501 as an optimization while qualifying columns for tables with lots of columns. 502 """ 503 504 def __init__(self, keys: Collection[K], value: V): 505 self._keys = keys if isinstance(keys, Set) else set(keys) 506 self._value = value 507 508 def __getitem__(self, key: K) -> V: 509 if key in self._keys: 510 return self._value 511 raise KeyError(key) 512 513 def __len__(self) -> int: 514 return len(self._keys) 515 516 def __iter__(self) -> Iterator[K]: 517 return iter(self._keys)
Mapping where all keys return the same value.
This rigamarole is meant to avoid copying keys, which was originally intended as an optimization while qualifying columns for tables with lots of columns.