Skip to content

Instantly share code, notes, and snippets.

@cartercanedy
Last active November 1, 2023 21:58
Show Gist options
  • Save cartercanedy/7c2184f3829d2c447afbc4e011218750 to your computer and use it in GitHub Desktop.
Save cartercanedy/7c2184f3829d2c447afbc4e011218750 to your computer and use it in GitHub Desktop.
Pure Python sequence query functions using Python 3.12+ generic type syntax
from typing import (
Sequence,
Iterable,
Callable
)
type Predicate[ T ] = Callable[ [ T ] , bool ]
type Converter[ TIn , TOut ] = Callable[ [ TIn ] , TOut ]
class QueryException( Exception ):
def __init__( self , *args , **kwargs ):
super().__init__( *args , **kwargs )
def createmask[ T ]( items : Iterable[ T ] , pred : Predicate[ T ] ) -> Sequence[ bool ]:
return [ pred( item ) for item in items ]
def applymask[ T ]( items : Sequence[ T ] , mask : Sequence[ bool ] ) -> Sequence[ T | None ]:
if len( items ) != len( mask ):
raise QueryException( "length of items not equal to length of mask supplied" )
return [ item if mask[ i ] else None for i , item in enumerate( items ) ]
def where[ T ]( items : Sequence[ T ] , pred : Predicate[ T ] ) -> Sequence[ T ]:
new_items : list[ T ] = []
for item in items: if pred( item ): new_items.append( item )
return new_items
def select[ TIn , TOut ]( items: Iterable[ TIn ] , converter : Converter[ TIn , TOut ] ) -> Sequence[ TOut ]:
return [ converter( item ) for item in items ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment