index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
10,497
typing
__repr__
null
def __repr__(self): return f'ForwardRef({self.__forward_arg__!r})'
(self)
10,498
typing
_evaluate
null
def _evaluate(self, globalns, localns, recursive_guard): if self.__forward_arg__ in recursive_guard: return self if not self.__forward_evaluated__ or localns is not globalns: if globalns is None and localns is None: globalns = localns = {} elif globalns is None: globalns = localns elif localns is None: localns = globalns if self.__forward_module__ is not None: globalns = getattr( sys.modules.get(self.__forward_module__, None), '__dict__', globalns ) type_ = _type_check( eval(self.__forward_code__, globalns, localns), "Forward references must evaluate to types.", is_argument=self.__forward_is_argument__, allow_special_forms=self.__forward_is_class__, ) self.__forward_value__ = _eval_type( type_, globalns, localns, recursive_guard | {self.__forward_arg__} ) self.__forward_evaluated__ = True return self.__forward_value__
(self, globalns, localns, recursive_guard)
10,575
typing
get_args
Get type arguments with all substitutions performed. For unions, basic simplifications used by Union constructor are performed. Examples:: get_args(Dict[str, int]) == (str, int) get_args(int) == () get_args(Union[int, Union[T, int], str][int]) == (int, str) get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) get_args(Callable[[], T][int]) == ([], int)
def get_args(tp): """Get type arguments with all substitutions performed. For unions, basic simplifications used by Union constructor are performed. Examples:: get_args(Dict[str, int]) == (str, int) get_args(int) == () get_args(Union[int, Union[T, int], str][int]) == (int, str) get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) get_args(Callable[[], T][int]) == ([], int) """ if isinstance(tp, _AnnotatedAlias): return (tp.__origin__,) + tp.__metadata__ if isinstance(tp, (_GenericAlias, GenericAlias)): res = tp.__args__ if (tp.__origin__ is collections.abc.Callable and not (len(res) == 2 and _is_param_expr(res[0]))): res = (list(res[:-1]), res[-1]) return res if isinstance(tp, types.UnionType): return tp.__args__ return ()
(tp)
10,576
datclass
get_datclass
Get a decorator that can be used to convert a dataclass to a datclass. :param extra: Whether to extend fields. :param log: Whether to log missing fields, including undefined fields. :param identifier_transform: A function that maps any field name to a valid Python field name. :param empty_dict_as_none: Convert empty dict to None when converting to a DataClass. :param nested: Whether to recursively convert nested dataclasses. :return: A class that extends a dataclass.
def get_datclass( extra: bool = True, log: bool = True, identifier_transform: Callable[[str], str] = get_identifier, empty_dict_as_none=False, nested: bool = True, ): """Get a decorator that can be used to convert a dataclass to a datclass. :param extra: Whether to extend fields. :param log: Whether to log missing fields, including undefined fields. :param identifier_transform: A function that maps any field name to a valid Python field name. :param empty_dict_as_none: Convert empty dict to None when converting to a DataClass. :param nested: Whether to recursively convert nested dataclasses. :return: A class that extends a dataclass. """ def to_item(v, ignore_none=False): """Convert v to a dictionary or a list. :param v: :param ignore_none: Ignore values that are None. :return: """ if isinstance(v, Datclass): v = v.to_dict(ignore_none=ignore_none) elif isinstance(v, list): v = [to_item(i, ignore_none=ignore_none) for i in v] return v def convert_attr_value(value, type_, cls): """Convert the value of the attribute. :param value: :param type_: :param cls: :return: """ if value is None: return None if empty_dict_as_none and value == {}: return None origin = get_origin(type_) if origin is None and isinstance(value, dict): if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, ForwardRef): type_ = sys.modules[cls.__module__].__dict__[type_.__forward_arg__] if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, str): type_ = sys.modules[cls.__module__].__dict__[type_] if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, TypeVar): # Generic type_ = type_.__bound__ if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif origin is list: args_ = get_args(type_) if args_: type_ = args_[0] value = [convert_attr_value(i, type_, cls) for i in value] elif origin is Union: types_ = get_args(type_) if len(types_) == 2 and NoneType in types_: # Optional if types_[0] is NoneType: type_ = types_[1] else: type_ = types_[0] value = convert_attr_value(value, type_, cls) return value class Datclass: def __new__(cls, *args, **kwargs): """Modify the `__init__` function to support extended attributes.""" if _ORIGINAL_INIT_NAME not in cls.__dict__: # Each time an object is instantiated, it enters the `__new__` method; # let's add a conditional check here. setattr(cls, _ORIGINAL_INIT_NAME, cls.__init__) cls.__init__ = cls.__datclass_init__ return super().__new__(cls) def __datclass_init__(self, *args, **kwargs): """A new constructor that extends the original constructor. :param self: Instances of a class that inherits from __dataclass__. :param args: :param kwargs: :return: """ # All code assumes that "cls" is a dataclass and a subclass of "__dataclass__", # eliminating the need for further checks. cls = self.__class__ if cls is Datclass: # Handling Generic Types and Creating Objects Directly using DataClass. for attr, value in kwargs.items(): if empty_dict_as_none and value == {}: value = None setattr(self, attr, value) return # Map any field name to a valid Python field name. kwargs = {cls.__rename_attrs__.get(k, k): v for k, v in kwargs.items()} # Call the original constructor. original_init = getattr(self, _ORIGINAL_INIT_NAME) init_kwargs = {k: kwargs.pop(k) for k in self.__dataclass_fields__ if k in kwargs} # type: ignore original_init(*args, **init_kwargs) # Extend fields or log missing fields, including undefined fields. if extra or log: frozen = cls.__dataclass_params__.frozen # type: ignore for attr, value in kwargs.items(): ok_attr = identifier_transform(attr) if log: # Log missing fields, including undefined fields. # Facilitate Timely Data Updates log_message = f'{cls.__module__}.{cls.__name__}({ok_attr}: {type(value).__name__} = {value!r})' if ok_attr != attr: log_message += f' # rename from {attr!r}' _log.warning(log_message) if not frozen and extra: setattr(self, ok_attr, value) # Record the renaming of fields. if ok_attr != attr and attr not in self.__rename_attrs__: self.__rename_attrs__[attr] = ok_attr # noinspection PyUnusedLocal def __post_init__(self, *args, **kwargs): """Handling nested dataclasses. The `__post_init__` in subclasses must call this method, otherwise nested dataclasses cannot be processed. About `get_origin` and `get_args` -------------------------------- `get_origin` and `get_args` are used to handle generic types. Examples: >>> from typing import get_origin, get_args >>> from typing import List, Dict, Tuple, Union, Optional >>> >>> assert get_origin(List[int]) is list ... assert get_origin(Dict[str, int]) is dict ... assert get_origin(Optional[int]) is Union ... # assert get_origin(<other>) is None ... >>> assert get_args(List[int]) == (int,) ... assert get_args(Union[int, str]) == (int, str) ... # assert get_args(Optional[int]) == (int, NoneType) ... """ if not nested: return for attr_name, field in self.__dataclass_fields__.items(): # type: ignore value = getattr(self, attr_name) new_value = convert_attr_value(value, field.type, self.__class__) if new_value is not value: setattr(self, attr_name, new_value) # Original field name -> Valid Python field name after renaming __rename_attrs__: ClassVar[Dict[str, str]] = {} @classmethod def from_str(cls, text: str): """Create an instance from a JSON string.""" return cls(**json.loads(text)) @classmethod def from_file(cls, file_path: str, encoding: str = 'utf8'): """Create an instance from a JSON file.""" text = Path(file_path).read_text(encoding=encoding) return cls.from_str(text) def to_dict(self, ignore_none=False, recursive_ignore=True) -> dict: """Convert an instance to a dictionary. :param ignore_none: Ignore values that are None. :param recursive_ignore: Ignore values that are None recursively. :return: """ rename_attrs_inverse = {v: k for k, v in self.__rename_attrs__.items()} result_dict, object_attrs = {}, {} if hasattr(self, '__slots__'): object_attrs.update({k: getattr(self, k) for k in self.__slots__}) object_attrs.update(self.__dict__) for attr_name, attr_value in object_attrs.items(): # Exclude private attributes: # '__orig_class__' if attr_name.startswith('__'): continue if attr_value is None and ignore_none: continue target_attr_name = rename_attrs_inverse.get(attr_name, attr_name) transformed_value = to_item(attr_value, ignore_none=ignore_none and recursive_ignore) result_dict[target_attr_name] = transformed_value return result_dict def to_str( self, ensure_ascii=True, indent=None, ignore_none=False, sort_keys=False, recursive_ignore=True ) -> str: """Convert an instance to a JSON string. :param ensure_ascii: same as json dumps :param indent: same as json dumps :param ignore_none: Ignore values that are None. :param sort_keys: same as json dumps :param recursive_ignore: Ignore values that are None recursively. :return: """ data_dict = self.to_dict( ignore_none=ignore_none, recursive_ignore=recursive_ignore ) json_str = json.dumps( data_dict, ensure_ascii=ensure_ascii, indent=indent, sort_keys=sort_keys ) return json_str def to_file(self, file_path: str, encoding: str = 'utf8', ensure_ascii=True, indent=None, ignore_none=False, sort_keys=False): """Convert an instance to a JSON file. :param file_path: Save file path. :param encoding: same as json dumps :param ensure_ascii: same as json dumps :param indent: same as json dumps :param ignore_none: Ignore values that are None. :param sort_keys: same as json dumps :return: """ Path(file_path).write_text( self.to_str( ensure_ascii=ensure_ascii, indent=indent, ignore_none=ignore_none, sort_keys=sort_keys ), encoding=encoding, ) return Datclass
(extra: bool = True, log: bool = True, identifier_transform: Callable[[str], str] = <function get_identifier at 0x7f4dac8d7eb0>, empty_dict_as_none=False, nested: bool = True)
10,577
datclass.utils
get_identifier
null
def get_identifier(name: str): # Query the cache. if name in _NAME_MAP: return _NAME_MAP[name] # Process fields starting with double (or multiple) underscores by replacing them with a single underscore. if name.startswith('__'): name = '_' + name.lstrip('_') # If it's a keyword, add an '_' suffix. if keyword.iskeyword(name): s = f'{name}_' elif name.isidentifier(): # Keywords are valid identifiers, so first check for keywords, and then check for identifiers. s = name else: # First, replace '-' with '_'. name = name.replace('-', '_') # If it's not a standard identifier, filter out characters other than underscores, # lowercase letters, uppercase letters, and numbers. s = ''.join(filter(lambda c: c in '_' + string.ascii_letters + string.digits, name)) if s: if s[0] in string.digits: s = f'a_{s}' # attribute elif keyword.iskeyword(s): s = f'{s}_' elif not s.isidentifier(): s = get_md5_identifier(name) else: s = get_md5_identifier(name) # Convert the first letter to lowercase. if s[0] in string.ascii_uppercase: s = s[0].lower() + s[1:] # Cache before returning. _NAME_MAP[name] = s return s
(name: str)
10,578
typing
get_origin
Get the unsubscripted version of a type. This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar and Annotated. Return None for unsupported types. Examples:: get_origin(Literal[42]) is Literal get_origin(int) is None get_origin(ClassVar[int]) is ClassVar get_origin(Generic) is Generic get_origin(Generic[T]) is Generic get_origin(Union[T, int]) is Union get_origin(List[Tuple[T, T]][int]) == list get_origin(P.args) is P
def get_origin(tp): """Get the unsubscripted version of a type. This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar and Annotated. Return None for unsupported types. Examples:: get_origin(Literal[42]) is Literal get_origin(int) is None get_origin(ClassVar[int]) is ClassVar get_origin(Generic) is Generic get_origin(Generic[T]) is Generic get_origin(Union[T, int]) is Union get_origin(List[Tuple[T, T]][int]) == list 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
(tp)
10,583
datclass.utils
write_file
null
def write_file(file_path, content, encoding='utf-8'): with open(file_path, 'w', encoding=encoding) as f: f.write(content)
(file_path, content, encoding='utf-8')
10,584
aiojobs._job
Job
null
class Job(Generic[_T]): def __init__( self, coro: Coroutine[object, object, _T], scheduler: Scheduler, name: Optional[str] = None, ): self._coro = coro self._scheduler: Optional[Scheduler] = scheduler self._name = name loop = asyncio.get_running_loop() self._started = loop.create_future() self._closed = False self._explicit = False self._task: Optional["asyncio.Task[_T]"] = None tb = traceback.extract_stack(sys._getframe(2)) if loop.get_debug() else None self._source_traceback = tb def __repr__(self) -> str: info = [] if self._closed: info.append("closed") elif self._task is None: info.append("pending") state = " ".join(info) if state: state += " " return f"<Job {state}coro=<{self._coro}>>" @property def active(self) -> bool: return not self.closed and not self.pending @property def pending(self) -> bool: return self._task is None and not self.closed @property def closed(self) -> bool: return self._closed def get_name(self) -> Optional[str]: """Get the task name. See https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.get_name. Returns None if no name was set on the Job object and job has not yet started. """ return self._task.get_name() if self._task else self._name def set_name(self, name: str) -> None: self._name = name if self._task is not None: self._task.set_name(name) async def _do_wait(self, timeout: Optional[float]) -> _T: async with asyncio_timeout(timeout): # TODO: add a test for waiting for a pending coro await self._started assert self._task is not None # Task should have been created before this. return await self._task async def wait(self, *, timeout: Optional[float] = None) -> _T: if self._closed: assert self._task is not None # Task must have been created if closed. return await self._task assert self._scheduler is not None # Only removed when not _closed. self._explicit = True scheduler = self._scheduler try: return await asyncio.shield(self._do_wait(timeout)) except asyncio.CancelledError: # Don't stop inner coroutine on explicit cancel raise except Exception: await self._close(scheduler.close_timeout) raise async def close(self, *, timeout: Optional[float] = None) -> None: if self._closed: return assert self._scheduler is not None # Only removed when not _closed. self._explicit = True if timeout is None: timeout = self._scheduler.close_timeout await self._close(timeout) async def _close(self, timeout: Optional[float]) -> None: self._closed = True if self._task is None: # the task is closed immediately without actual execution # it prevents a warning like # RuntimeWarning: coroutine 'coro' was never awaited self._start() assert self._task is not None self._task.cancel() # self._scheduler is None after _done_callback() scheduler = self._scheduler try: async with asyncio_timeout(timeout): await self._task except asyncio.CancelledError: pass except asyncio.TimeoutError as exc: if self._explicit: raise context = { "message": "Job closing timed out", "job": self, "exception": exc, } if self._source_traceback is not None: context["source_traceback"] = self._source_traceback # scheduler is only None if job was already finished, in which case # there's no timeout. self._scheduler will now be None though. assert scheduler is not None scheduler.call_exception_handler(context) except Exception: if self._explicit: raise def _start(self) -> None: assert self._task is None self._task = asyncio.create_task(self._coro, name=self._name) self._task.add_done_callback(self._done_callback) self._started.set_result(None) def _done_callback(self, task: "asyncio.Task[_T]") -> None: assert self._scheduler is not None scheduler = self._scheduler scheduler._done(self) try: exc = task.exception() except asyncio.CancelledError: pass else: if exc is not None and not self._explicit: self._report_exception(exc) scheduler._failed_tasks.put_nowait(task) self._scheduler = None # drop backref self._closed = True def _report_exception(self, exc: BaseException) -> None: assert self._scheduler is not None context = {"message": "Job processing failed", "job": self, "exception": exc} if self._source_traceback is not None: context["source_traceback"] = self._source_traceback self._scheduler.call_exception_handler(context)
(coro: Coroutine[object, object, +_T], scheduler: None, name: Optional[str] = None)
10,585
aiojobs._job
__init__
null
def __init__( self, coro: Coroutine[object, object, _T], scheduler: Scheduler, name: Optional[str] = None, ): self._coro = coro self._scheduler: Optional[Scheduler] = scheduler self._name = name loop = asyncio.get_running_loop() self._started = loop.create_future() self._closed = False self._explicit = False self._task: Optional["asyncio.Task[_T]"] = None tb = traceback.extract_stack(sys._getframe(2)) if loop.get_debug() else None self._source_traceback = tb
(self, coro: Coroutine[object, object, +_T], scheduler: NoneType, name: Optional[str] = None)
10,586
aiojobs._job
__repr__
null
def __repr__(self) -> str: info = [] if self._closed: info.append("closed") elif self._task is None: info.append("pending") state = " ".join(info) if state: state += " " return f"<Job {state}coro=<{self._coro}>>"
(self) -> str
10,587
aiojobs._job
_close
null
def set_name(self, name: str) -> None: self._name = name if self._task is not None: self._task.set_name(name)
(self, timeout: Optional[float]) -> NoneType
10,589
aiojobs._job
_done_callback
null
def _done_callback(self, task: "asyncio.Task[_T]") -> None: assert self._scheduler is not None scheduler = self._scheduler scheduler._done(self) try: exc = task.exception() except asyncio.CancelledError: pass else: if exc is not None and not self._explicit: self._report_exception(exc) scheduler._failed_tasks.put_nowait(task) self._scheduler = None # drop backref self._closed = True
(self, task: _asyncio.Task[+_T]) -> NoneType
10,590
aiojobs._job
_report_exception
null
def _report_exception(self, exc: BaseException) -> None: assert self._scheduler is not None context = {"message": "Job processing failed", "job": self, "exception": exc} if self._source_traceback is not None: context["source_traceback"] = self._source_traceback self._scheduler.call_exception_handler(context)
(self, exc: BaseException) -> NoneType
10,591
aiojobs._job
_start
null
def _start(self) -> None: assert self._task is None self._task = asyncio.create_task(self._coro, name=self._name) self._task.add_done_callback(self._done_callback) self._started.set_result(None)
(self) -> NoneType
10,593
aiojobs._job
get_name
Get the task name. See https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.get_name. Returns None if no name was set on the Job object and job has not yet started.
def get_name(self) -> Optional[str]: """Get the task name. See https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.get_name. Returns None if no name was set on the Job object and job has not yet started. """ return self._task.get_name() if self._task else self._name
(self) -> Optional[str]
10,596
aiojobs._scheduler
Scheduler
null
class Scheduler(Collection[Job[object]]): def __init__( self, *, close_timeout: Optional[float] = 0.1, limit: Optional[int] = 100, pending_limit: int = 10000, exception_handler: Optional[ExceptionHandler] = None, ): if exception_handler is not None and not callable(exception_handler): raise TypeError( "A callable object or None is expected, " "got {!r}".format(exception_handler) ) self._jobs: Set[Job[object]] = set() self._close_timeout = close_timeout self._limit = limit self._exception_handler = exception_handler self._failed_tasks: asyncio.Queue[ Optional[asyncio.Task[object]] ] = asyncio.Queue() self._failed_task = asyncio.create_task(self._wait_failed()) self._pending: asyncio.Queue[Job[object]] = asyncio.Queue(maxsize=pending_limit) self._closed = False def __iter__(self) -> Iterator[Job[Any]]: return iter(self._jobs) def __len__(self) -> int: return len(self._jobs) def __contains__(self, obj: object) -> bool: return obj in self._jobs def __repr__(self) -> str: info = [] if self._closed: info.append("closed") state = " ".join(info) if state: state += " " return f"<Scheduler {state}jobs={len(self)}>" @property def limit(self) -> Optional[int]: return self._limit @property def pending_limit(self) -> int: return self._pending.maxsize @property def close_timeout(self) -> Optional[float]: return self._close_timeout @property def active_count(self) -> int: return len(self._jobs) - self._pending.qsize() @property def pending_count(self) -> int: return self._pending.qsize() @property def closed(self) -> bool: return self._closed async def spawn( self, coro: Coroutine[object, object, _T], name: Optional[str] = None ) -> Job[_T]: if self._closed: raise RuntimeError("Scheduling a new job after closing") job = Job(coro, self, name=name) should_start = self._limit is None or self.active_count < self._limit if should_start: job._start() else: try: # wait for free slot in queue await self._pending.put(job) except asyncio.CancelledError: await job.close() raise self._jobs.add(job) return job async def close(self) -> None: if self._closed: return self._closed = True # prevent adding new jobs jobs = self._jobs if jobs: # cleanup pending queue # all job will be started on closing while not self._pending.empty(): self._pending.get_nowait() await asyncio.gather( *[job._close(self._close_timeout) for job in jobs], return_exceptions=True, ) self._jobs.clear() self._failed_tasks.put_nowait(None) await self._failed_task def call_exception_handler(self, context: Dict[str, Any]) -> None: if self._exception_handler is None: asyncio.get_running_loop().call_exception_handler(context) else: self._exception_handler(self, context) @property def exception_handler(self) -> Optional[ExceptionHandler]: return self._exception_handler def _done(self, job: Job[object]) -> None: self._jobs.discard(job) if not self.pending_count: return # No pending jobs when limit is None # Safe to subtract. ntodo = self._limit - self.active_count # type: ignore[operator] i = 0 while i < ntodo: if not self.pending_count: return new_job = self._pending.get_nowait() if new_job.closed: continue new_job._start() i += 1 async def _wait_failed(self) -> None: # a coroutine for waiting failed tasks # without awaiting for failed tasks async raises a warning while True: task = await self._failed_tasks.get() if task is None: return # closing try: await task # should raise exception except Exception: # Cleanup a warning # self.call_exception_handler() is already called # by Job._add_done_callback # Thus we caught an task exception and we are good citizens pass
(*, close_timeout: Optional[float] = 0.1, limit: Optional[int] = 100, pending_limit: int = 10000, exception_handler: Optional[Callable[[ForwardRef('Scheduler'), Dict[str, Any]], NoneType]] = None)
10,597
aiojobs._scheduler
__contains__
null
def __contains__(self, obj: object) -> bool: return obj in self._jobs
(self, obj: object) -> bool
10,598
aiojobs._scheduler
__init__
null
def __init__( self, *, close_timeout: Optional[float] = 0.1, limit: Optional[int] = 100, pending_limit: int = 10000, exception_handler: Optional[ExceptionHandler] = None, ): if exception_handler is not None and not callable(exception_handler): raise TypeError( "A callable object or None is expected, " "got {!r}".format(exception_handler) ) self._jobs: Set[Job[object]] = set() self._close_timeout = close_timeout self._limit = limit self._exception_handler = exception_handler self._failed_tasks: asyncio.Queue[ Optional[asyncio.Task[object]] ] = asyncio.Queue() self._failed_task = asyncio.create_task(self._wait_failed()) self._pending: asyncio.Queue[Job[object]] = asyncio.Queue(maxsize=pending_limit) self._closed = False
(self, *, close_timeout: Optional[float] = 0.1, limit: Optional[int] = 100, pending_limit: int = 10000, exception_handler: Optional[Callable[[aiojobs._scheduler.Scheduler, Dict[str, Any]], NoneType]] = None)
10,599
aiojobs._scheduler
__iter__
null
def __iter__(self) -> Iterator[Job[Any]]: return iter(self._jobs)
(self) -> Iterator[aiojobs._job.Job[Any]]
10,600
aiojobs._scheduler
__len__
null
def __len__(self) -> int: return len(self._jobs)
(self) -> int
10,601
aiojobs._scheduler
__repr__
null
def __repr__(self) -> str: info = [] if self._closed: info.append("closed") state = " ".join(info) if state: state += " " return f"<Scheduler {state}jobs={len(self)}>"
(self) -> str
10,602
aiojobs._scheduler
_done
null
def _done(self, job: Job[object]) -> None: self._jobs.discard(job) if not self.pending_count: return # No pending jobs when limit is None # Safe to subtract. ntodo = self._limit - self.active_count # type: ignore[operator] i = 0 while i < ntodo: if not self.pending_count: return new_job = self._pending.get_nowait() if new_job.closed: continue new_job._start() i += 1
(self, job: aiojobs._job.Job[object]) -> NoneType
10,604
aiojobs._scheduler
call_exception_handler
null
def call_exception_handler(self, context: Dict[str, Any]) -> None: if self._exception_handler is None: asyncio.get_running_loop().call_exception_handler(context) else: self._exception_handler(self, context)
(self, context: Dict[str, Any]) -> NoneType
10,605
aiojobs._scheduler
close
null
@property def closed(self) -> bool: return self._closed
(self) -> NoneType
10,609
aiojobs
create_scheduler
null
"""Jobs scheduler for managing background task (asyncio). The library gives controlled way for scheduling background tasks for asyncio applications. """ import warnings from typing import Optional from ._job import Job from ._scheduler import ExceptionHandler, Scheduler __version__ = "1.2.1" async def create_scheduler( *, close_timeout: Optional[float] = 0.1, limit: Optional[int] = 100, pending_limit: int = 10000, exception_handler: Optional[ExceptionHandler] = None ) -> Scheduler: warnings.warn("Scheduler can now be instantiated directly.", DeprecationWarning) if exception_handler is not None and not callable(exception_handler): raise TypeError( "A callable object or None is expected, " "got {!r}".format(exception_handler) ) return Scheduler( close_timeout=close_timeout, limit=limit, pending_limit=pending_limit, exception_handler=exception_handler, )
(*, close_timeout: Optional[float] = 0.1, limit: Optional[int] = 100, pending_limit: int = 10000, exception_handler: Optional[Callable[[aiojobs._scheduler.Scheduler, Dict[str, Any]], NoneType]] = None) -> aiojobs._scheduler.Scheduler
10,611
retask.exceptions
ConnectionError
A Connection error occurred.
class ConnectionError(RetaskException): """A Connection error occurred."""
null
10,612
retask.queue
Job
Job object containing the result from the workers. :arg rdb: The underlying redis connection.
class Job(object): """ Job object containing the result from the workers. :arg rdb: The underlying redis connection. """ def __init__(self, rdb): self.rdb = rdb self.urn = uuid.uuid4().urn self.__result = None @property def result(self): """ Returns the result from the worker for this job. This is used to pass result in async way. """ if self.__result: return self.__result data = self.rdb.rpop(self.urn) if data: self.rdb.delete(self.urn) data = json.loads(data) self.__result = data return data else: return None def wait(self, wait_time=0): """ Blocking call to check if the worker returns the result. One can use job.result after this call returns ``True``. :arg wait_time: Time in seconds to wait, default is infinite. :return: `True` or `False`. .. note:: This is a blocking call, you can specity wait_time argument for timeout. """ if self.__result: return True data = self.rdb.brpop(self.urn, wait_time) if data: self.rdb.delete(self.urn) data = json.loads(data[1]) self.__result = data return True else: return False
(rdb)
10,613
retask.queue
__init__
null
def __init__(self, rdb): self.rdb = rdb self.urn = uuid.uuid4().urn self.__result = None
(self, rdb)
10,614
retask.queue
wait
Blocking call to check if the worker returns the result. One can use job.result after this call returns ``True``. :arg wait_time: Time in seconds to wait, default is infinite. :return: `True` or `False`. .. note:: This is a blocking call, you can specity wait_time argument for timeout.
def wait(self, wait_time=0): """ Blocking call to check if the worker returns the result. One can use job.result after this call returns ``True``. :arg wait_time: Time in seconds to wait, default is infinite. :return: `True` or `False`. .. note:: This is a blocking call, you can specity wait_time argument for timeout. """ if self.__result: return True data = self.rdb.brpop(self.urn, wait_time) if data: self.rdb.delete(self.urn) data = json.loads(data[1]) self.__result = data return True else: return False
(self, wait_time=0)
10,615
retask.queue
Queue
Returns the ``Queue`` object with the given name. If the user passes optional config dictionary with details for Redis server, it will connect to that instance. By default it connects to the localhost.
class Queue(object): """ Returns the ``Queue`` object with the given name. If the user passes optional config dictionary with details for Redis server, it will connect to that instance. By default it connects to the localhost. """ def __init__(self, name: str, config: Optional[dict[str,Any]]= None): self.name = name self._name = 'retaskqueue-' + name self.config = { 'host': 'localhost', 'port': 6379, 'db': 0, 'password': None, } if config: self.config.update(config) self.rdb: Redis[bytes] self.connected: bool = False def names(self) -> list[bytes]: """ Returns a list of queues available, ``None`` if no such queues found. Remember this will only show queues with at least one item enqueued. """ data = None if not self.connected: raise ConnectionError('Queue is not connected') try: data = self.rdb.keys("retaskqueue-*") except redis.exceptions.ConnectionError as err: raise ConnectionError(str(err)) return [name[12:] for name in data] @property def length(self) -> int: """ Gives the length of the queue. Returns ``None`` if the queue is not connected. If the queue is not connected then it will raise :class:`retask.ConnectionError`. """ if not self.connected: raise ConnectionError('Queue is not connected') try: length = self.rdb.llen(self._name) except redis.exceptions.ConnectionError as err: raise ConnectionError(str(err)) return length def connect(self) -> bool: """ Creates the connection with the redis server. Return ``True`` if the connection works, else returns ``False``. It does not take any arguments. :return: ``Boolean`` value .. note:: After creating the ``Queue`` object the user should call the ``connect`` method to create the connection. .. doctest:: >>> from retask import Queue >>> q = Queue('test') >>> q.connect() True """ config = self.config self.rdb = redis.Redis(config['host'], config['port'], config['db'],\ config['password']) try: info = self.rdb.info() self.connected = True except redis.ConnectionError: return False return True def wait(self, wait_time=0) -> Union[Task, bool]: """ Returns a :class:`~retask.task.Task` object from the queue. Returns ``False`` if it timeouts. :arg wait_time: Time in seconds to wait, default is infinite. :return: :class:`~retask.task.Task` object from the queue or False if it timeouts. .. doctest:: >>> from retask import Queue >>> q = Queue('test') >>> q.connect() True >>> task = q.wait() >>> print(task.data) {u'name': u'kushal'} .. note:: This is a blocking call, you can specity wait_time argument for timeout. """ if not self.connected: raise ConnectionError('Queue is not connected') data = self.rdb.brpop(self._name, wait_time) if data: task = Task() task.__dict__ = json.loads(data[1]) return task else: return False def dequeue(self) -> Optional[Task]: """ Returns a :class:`~retask.task.Task` object from the queue. Returns ``None`` if the queue is empty. :return: :class:`~retask.task.Task` object from the queue If the queue is not connected then it will raise :class:`retask.ConnectionError` .. doctest:: >>> from retask import Queue >>> q = Queue('test') >>> q.connect() True >>> t = q.dequeue() >>> print(t.data) {u'name': u'kushal'} """ if not self.connected: raise ConnectionError('Queue is not connected') if self.rdb.llen(self._name) == 0: return None data = self.rdb.rpop(self._name) if not data: return None # redis returns bytes sdata = data.decode("utf-8") task = Task() task.__dict__ = json.loads(sdata) return task def enqueue(self, task): """ Enqueues the given :class:`~retask.task.Task` object to the queue and returns a :class:`~retask.queue.Job` object. :arg task: ::class:`~retask.task.Task` object :return: :class:`~retask.queue.Job` object If the queue is not connected then it will raise :class:`retask.ConnectionError`. .. doctest:: >>> from retask import Queue >>> q = Queue('test') >>> q.connect() True >>> from retask.task import Task >>> task = Task({'name':'kushal'}) >>> job = q.enqueue(task) """ if not self.connected: raise ConnectionError('Queue is not connected') try: #We can set the value to the queue job = Job(self.rdb) task.urn = job.urn text = json.dumps(task.__dict__) self.rdb.lpush(self._name, text) except Exception as err: return False return job def send(self, task: Task, result, expire: int=60): """ Sends the result back to the producer. This should be called if only you want to return the result in async manner. :arg task: ::class:`~retask.task.Task` object :arg result: Result data to be send back. Should be in JSON serializable. :arg expire: Time in seconds after the key expires. Default is 60 seconds. """ self.rdb.lpush(task.urn, json.dumps(result)) self.rdb.expire(task.urn, expire) def __repr__(self): if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, self.name) def find(self, obj): """Returns the index of the given object in the queue, it might be string which will be searched inside each task. :arg obj: object we are looking :return: -1 if the object is not found or else the location of the task """ if not self.connected: raise ConnectionError('Queue is not connected') data = self.rdb.lrange(self._name, 0, -1) for i, datum in enumerate(data): if datum.find(str(obj)) != -1: return i return -1
(name: str, config: Optional[dict[str, Any]] = None)
10,616
retask.queue
__init__
null
def __init__(self, name: str, config: Optional[dict[str,Any]]= None): self.name = name self._name = 'retaskqueue-' + name self.config = { 'host': 'localhost', 'port': 6379, 'db': 0, 'password': None, } if config: self.config.update(config) self.rdb: Redis[bytes] self.connected: bool = False
(self, name: str, config: Optional[dict[str, Any]] = None)
10,617
retask.queue
__repr__
null
def __repr__(self): if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, self.name)
(self)
10,618
retask.queue
connect
Creates the connection with the redis server. Return ``True`` if the connection works, else returns ``False``. It does not take any arguments. :return: ``Boolean`` value .. note:: After creating the ``Queue`` object the user should call the ``connect`` method to create the connection. .. doctest:: >>> from retask import Queue >>> q = Queue('test') >>> q.connect() True
def connect(self) -> bool: """ Creates the connection with the redis server. Return ``True`` if the connection works, else returns ``False``. It does not take any arguments. :return: ``Boolean`` value .. note:: After creating the ``Queue`` object the user should call the ``connect`` method to create the connection. .. doctest:: >>> from retask import Queue >>> q = Queue('test') >>> q.connect() True """ config = self.config self.rdb = redis.Redis(config['host'], config['port'], config['db'],\ config['password']) try: info = self.rdb.info() self.connected = True except redis.ConnectionError: return False return True
(self) -> bool
10,619
retask.queue
dequeue
Returns a :class:`~retask.task.Task` object from the queue. Returns ``None`` if the queue is empty. :return: :class:`~retask.task.Task` object from the queue If the queue is not connected then it will raise :class:`retask.ConnectionError` .. doctest:: >>> from retask import Queue >>> q = Queue('test') >>> q.connect() True >>> t = q.dequeue() >>> print(t.data) {u'name': u'kushal'}
def dequeue(self) -> Optional[Task]: """ Returns a :class:`~retask.task.Task` object from the queue. Returns ``None`` if the queue is empty. :return: :class:`~retask.task.Task` object from the queue If the queue is not connected then it will raise :class:`retask.ConnectionError` .. doctest:: >>> from retask import Queue >>> q = Queue('test') >>> q.connect() True >>> t = q.dequeue() >>> print(t.data) {u'name': u'kushal'} """ if not self.connected: raise ConnectionError('Queue is not connected') if self.rdb.llen(self._name) == 0: return None data = self.rdb.rpop(self._name) if not data: return None # redis returns bytes sdata = data.decode("utf-8") task = Task() task.__dict__ = json.loads(sdata) return task
(self) -> Optional[retask.task.Task]
10,620
retask.queue
enqueue
Enqueues the given :class:`~retask.task.Task` object to the queue and returns a :class:`~retask.queue.Job` object. :arg task: ::class:`~retask.task.Task` object :return: :class:`~retask.queue.Job` object If the queue is not connected then it will raise :class:`retask.ConnectionError`. .. doctest:: >>> from retask import Queue >>> q = Queue('test') >>> q.connect() True >>> from retask.task import Task >>> task = Task({'name':'kushal'}) >>> job = q.enqueue(task)
def enqueue(self, task): """ Enqueues the given :class:`~retask.task.Task` object to the queue and returns a :class:`~retask.queue.Job` object. :arg task: ::class:`~retask.task.Task` object :return: :class:`~retask.queue.Job` object If the queue is not connected then it will raise :class:`retask.ConnectionError`. .. doctest:: >>> from retask import Queue >>> q = Queue('test') >>> q.connect() True >>> from retask.task import Task >>> task = Task({'name':'kushal'}) >>> job = q.enqueue(task) """ if not self.connected: raise ConnectionError('Queue is not connected') try: #We can set the value to the queue job = Job(self.rdb) task.urn = job.urn text = json.dumps(task.__dict__) self.rdb.lpush(self._name, text) except Exception as err: return False return job
(self, task)
10,621
retask.queue
find
Returns the index of the given object in the queue, it might be string which will be searched inside each task. :arg obj: object we are looking :return: -1 if the object is not found or else the location of the task
def find(self, obj): """Returns the index of the given object in the queue, it might be string which will be searched inside each task. :arg obj: object we are looking :return: -1 if the object is not found or else the location of the task """ if not self.connected: raise ConnectionError('Queue is not connected') data = self.rdb.lrange(self._name, 0, -1) for i, datum in enumerate(data): if datum.find(str(obj)) != -1: return i return -1
(self, obj)
10,622
retask.queue
names
Returns a list of queues available, ``None`` if no such queues found. Remember this will only show queues with at least one item enqueued.
def names(self) -> list[bytes]: """ Returns a list of queues available, ``None`` if no such queues found. Remember this will only show queues with at least one item enqueued. """ data = None if not self.connected: raise ConnectionError('Queue is not connected') try: data = self.rdb.keys("retaskqueue-*") except redis.exceptions.ConnectionError as err: raise ConnectionError(str(err)) return [name[12:] for name in data]
(self) -> list[bytes]
10,623
retask.queue
send
Sends the result back to the producer. This should be called if only you want to return the result in async manner. :arg task: ::class:`~retask.task.Task` object :arg result: Result data to be send back. Should be in JSON serializable. :arg expire: Time in seconds after the key expires. Default is 60 seconds.
def send(self, task: Task, result, expire: int=60): """ Sends the result back to the producer. This should be called if only you want to return the result in async manner. :arg task: ::class:`~retask.task.Task` object :arg result: Result data to be send back. Should be in JSON serializable. :arg expire: Time in seconds after the key expires. Default is 60 seconds. """ self.rdb.lpush(task.urn, json.dumps(result)) self.rdb.expire(task.urn, expire)
(self, task: retask.task.Task, result, expire: int = 60)
10,624
retask.queue
wait
Returns a :class:`~retask.task.Task` object from the queue. Returns ``False`` if it timeouts. :arg wait_time: Time in seconds to wait, default is infinite. :return: :class:`~retask.task.Task` object from the queue or False if it timeouts. .. doctest:: >>> from retask import Queue >>> q = Queue('test') >>> q.connect() True >>> task = q.wait() >>> print(task.data) {u'name': u'kushal'} .. note:: This is a blocking call, you can specity wait_time argument for timeout.
def wait(self, wait_time=0) -> Union[Task, bool]: """ Returns a :class:`~retask.task.Task` object from the queue. Returns ``False`` if it timeouts. :arg wait_time: Time in seconds to wait, default is infinite. :return: :class:`~retask.task.Task` object from the queue or False if it timeouts. .. doctest:: >>> from retask import Queue >>> q = Queue('test') >>> q.connect() True >>> task = q.wait() >>> print(task.data) {u'name': u'kushal'} .. note:: This is a blocking call, you can specity wait_time argument for timeout. """ if not self.connected: raise ConnectionError('Queue is not connected') data = self.rdb.brpop(self._name, wait_time) if data: task = Task() task.__dict__ = json.loads(data[1]) return task else: return False
(self, wait_time=0) -> Union[retask.task.Task, bool]
10,625
retask.exceptions
RetaskException
Some ambiguous exception occurred
class RetaskException(RuntimeError): """Some ambiguous exception occurred"""
null
10,626
retask.task
Task
Returns a new Task object, the information for the task is passed through argument ``data`` :kwarg data: Python object which contains information for the task. Should be serializable through ``JSON``. :kwarg raw: If we are receiving raw JSON encoded data. :kwarg urn: If we are supping the random URN value as str.
class Task(): """ Returns a new Task object, the information for the task is passed through argument ``data`` :kwarg data: Python object which contains information for the task. Should be serializable through ``JSON``. :kwarg raw: If we are receiving raw JSON encoded data. :kwarg urn: If we are supping the random URN value as str. """ def __init__(self, data: Optional[object]=None, raw=False, urn=Optional[str]): self._data: str = "" self.urn: str = "" if not raw and data: self._data = json.dumps(data) else: if isinstance(data, str): self._data = data if isinstance(urn, str): self.urn = urn @property def data(self) -> Any: """ The python object containing information for the current task """ return json.loads(self._data) @property def rawdata(self) -> str: """ The string representation of the actual python objects for the task .. note:: This should not be used directly by the users. This is for internal use only. """ return self._data def __repr__(self) -> str: return '%s(%s)' % (self.__class__.__name__, repr(self.data))
(data: Optional[object] = None, raw=False, urn=typing.Optional[str])
10,627
retask.task
__init__
null
def __init__(self, data: Optional[object]=None, raw=False, urn=Optional[str]): self._data: str = "" self.urn: str = "" if not raw and data: self._data = json.dumps(data) else: if isinstance(data, str): self._data = data if isinstance(urn, str): self.urn = urn
(self, data: Optional[object] = None, raw=False, urn=typing.Optional[str])
10,628
retask.task
__repr__
null
def __repr__(self) -> str: return '%s(%s)' % (self.__class__.__name__, repr(self.data))
(self) -> str
10,633
bunches.base
Bunch
Abstract base class for bunches collections. A Bunch differs from a general python Collection in 3 ways: 1) It must include an 'add' method which provides the default mechanism for adding new items to the collection. 'add' allows a subclass to designate the preferred method of adding to the collections's stored data without replacing other access methods. 2) A subclass must include a 'subset' method with optional 'include' and 'exclude' parameters for returning a subset of the Bunch subclass. 3) It supports the '+' operator being used to join a Bunch subclass instance of the same general type (Mapping, Sequence, tuple, etc.). The '+' operator calls the Bunch subclass 'add' method to implement how the added item(s) is/are added to the Bunch subclass instance. Args: contents (Collection[Any]): stored collection of items.
class Bunch(Collection, abc.ABC): # type: ignore """Abstract base class for bunches collections. A Bunch differs from a general python Collection in 3 ways: 1) It must include an 'add' method which provides the default mechanism for adding new items to the collection. 'add' allows a subclass to designate the preferred method of adding to the collections's stored data without replacing other access methods. 2) A subclass must include a 'subset' method with optional 'include' and 'exclude' parameters for returning a subset of the Bunch subclass. 3) It supports the '+' operator being used to join a Bunch subclass instance of the same general type (Mapping, Sequence, tuple, etc.). The '+' operator calls the Bunch subclass 'add' method to implement how the added item(s) is/are added to the Bunch subclass instance. Args: contents (Collection[Any]): stored collection of items. """ contents: Collection[Any] """ Required Subclass Methods """ @abc.abstractmethod def add(self, item: Any, *args: Any, **kwargs: Any) -> None: """Adds 'item' to 'contents'. Args: item (Any): item to add to 'contents'. """ pass @abc.abstractmethod def subset( self, include: Optional[Union[Sequence[Any], Any]] = None, exclude: Optional[Union[Sequence[Any], Any]] = None, *args: Any, **kwargs: Any) -> Bunch: """Returns a subclass with some items removed from 'contents'. Args: include (Optional[Union[Sequence[Any], Any]]): item(s) to include in the new Bunch. Defaults to None. exclude (Optional[Union[Sequence[Any], Any]]): item(s) to exclude in the new Bunch. Defaults to None. """ pass """ Dunder Methods """ def __add__(self, other: Any) -> None: """Combines argument with 'contents' using the 'add' method. Args: other (Any): item to add to 'contents' using the 'add' method. """ self.add(item = other) return def __iadd__(self, other: Any) -> None: """Combines argument with 'contents' using the 'add' method. Args: other (Any): item to add to 'contents' using the 'add' method. """ self.add(item = other) return def __iter__(self) -> Iterator[Any]: """Returns iterable of 'contents'. Returns: Iterator: of 'contents'. """ return iter(self.contents) def __len__(self) -> int: """Returns length of 'contents'. Returns: int: length of 'contents'. """ return len(self.contents) # def __str__(self) -> str: # """Returns prettier str representation of an instance. # Returns: # str: a formatted str of an instance. # """ # return amos.recap.beautify(item = self, package = 'bunches')
(contents: collections.abc.Collection[typing.Any]) -> None
10,634
bunches.base
__add__
Combines argument with 'contents' using the 'add' method. Args: other (Any): item to add to 'contents' using the 'add' method.
def __add__(self, other: Any) -> None: """Combines argument with 'contents' using the 'add' method. Args: other (Any): item to add to 'contents' using the 'add' method. """ self.add(item = other) return
(self, other: Any) -> NoneType
10,636
bunches.base
__eq__
null
""" base: base classes for extensible, flexible, lightweight containers Corey Rayburn Yung <[email protected]> Copyright 2021, Corey Rayburn Yung License: Apache-2.0 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. Contents: Proxy (Container): basic wrapper for a stored python object. Dunder methods attempt to intelligently apply access methods to either the wrapper or the wrapped item. Bunch (Collection, ABC): base class for all containers in the bunches package. It requires subclasses to have 'add' and 'subset' methods. To Do: Integrate ashford Kinds system when it is finished. Add in 'beautify' str representations from amos once those are finished. Fix Proxy setter. Currently, the wrapper and wrapped are not being set at the right time, likely due to the inner workings of 'hasattr'. Add '__str__' to Proxy to get complete representation of Proxy wrapped and wrapped item in 'contents'. """ from __future__ import annotations import abc from collections.abc import Collection, Container, Iterator, Sequence import dataclasses from typing import Any, Optional, Type, Union """ (Mostly) Transparent Wrapper """ # @dataclasses.dataclass # class Proxy(Container): # type: ignore # """Basic wrapper class. # A Proxy differs than an ordinary container in 2 significant ways: # 1) Access methods for getting, setting, and deleting try to # intelligently direct the user's call to the proxy or stored object. # So, for example, when a user tries to set an attribute on the proxy, # the method will replace an attribute that exists in the proxy if # one exists. But if there is no such attribute, the set method is # applied to the object stored in 'contents'. # 2) When an 'in' call is made, the '__contains__' method first looks to # see if the item is stored in 'contents' (if 'contents' is a # collection). If that check gets an errorr, the method then checks # if the item is equivalent to 'contents'. This allows a Proxy to be # agnostic as to the type of item(s) in 'contents' while returning the # expected result from an 'in' call. # Args: # contents (Optional[Any]): any stored item(s). Defaults to None. # ToDo: # Add more dunder methods to address less common and fringe cases for use # of a Proxy class. # """ # contents: Optional[Any] = None # """ Dunder Methods """ # def __contains__(self, item: Any) -> bool: # """Returns whether 'item' is in or equivalent to 'contents'. # Args: # item (Any): item to check versus 'contents' # Returns: # bool: if 'item' is in or equivalent to 'contents' (True). Otherwise, # it returns False. # """ # try: # return item in self.contents # except TypeError: # try: # return item is self.contents # except TypeError: # return item == self.contents # def __getattr__(self, attribute: str) -> Any: # """Looks for 'attribute' in 'contents'. # Args: # attribute (str): name of attribute to return. # Raises: # AttributeError: if 'attribute' is not found in 'contents'. # Returns: # Any: matching attribute. # """ # try: # return object.__getattribute__( # object.__getattribute__(self, 'contents'), attribute) # except AttributeError: # raise AttributeError( # f'{attribute} was not found in the Proxy or its contents') # def __setattr__(self, attribute: str, value: Any) -> None: # """Sets 'attribute' to 'value'. # If 'attribute' exists in this class instance, its new value is set to # 'value.' Otherwise, 'attribute' and 'value' are set in what is stored # in 'contents' # Args: # attribute (str): name of attribute to set. # value (Any): value to store in the attribute 'attribute'. # """ # print('test contents None', self.contents) # print('test hasattr', attribute, hasattr(self, attribute)) # if hasattr(self, attribute) or self.contents is None: # print('test setting proxy', attribute, value) # object.__setattr__(self, attribute, value) # else: # print('test setting wrapped', attribute, value) # object.__setattr__(self.contents, attribute, value) # def __delattr__(self, attribute: str) -> None: # """Deletes 'attribute'. # If 'attribute' exists in this class instance, it is deleted. Otherwise, # this method attempts to delete 'attribute' from what is stored in # 'contents' # Args: # attribute (str): name of attribute to set. # Raises: # AttributeError: if 'attribute' is neither found in a class instance # nor in 'contents'. # """ # try: # object.__delattr__(self, attribute) # except AttributeError: # try: # object.__delattr__(self.contents, attribute) # except AttributeError: # raise AttributeError( # f'{attribute} was not found in the Proxy or its contents') @dataclasses.dataclass # type: ignore class Bunch(Collection, abc.ABC): # type: ignore """Abstract base class for bunches collections. A Bunch differs from a general python Collection in 3 ways: 1) It must include an 'add' method which provides the default mechanism for adding new items to the collection. 'add' allows a subclass to designate the preferred method of adding to the collections's stored data without replacing other access methods. 2) A subclass must include a 'subset' method with optional 'include' and 'exclude' parameters for returning a subset of the Bunch subclass. 3) It supports the '+' operator being used to join a Bunch subclass instance of the same general type (Mapping, Sequence, tuple, etc.). The '+' operator calls the Bunch subclass 'add' method to implement how the added item(s) is/are added to the Bunch subclass instance. Args: contents (Collection[Any]): stored collection of items. """ contents: Collection[Any] """ Required Subclass Methods """ @abc.abstractmethod def add(self, item: Any, *args: Any, **kwargs: Any) -> None: """Adds 'item' to 'contents'. Args: item (Any): item to add to 'contents'. """ pass @abc.abstractmethod def subset( self, include: Optional[Union[Sequence[Any], Any]] = None, exclude: Optional[Union[Sequence[Any], Any]] = None, *args: Any, **kwargs: Any) -> Bunch: """Returns a subclass with some items removed from 'contents'. Args: include (Optional[Union[Sequence[Any], Any]]): item(s) to include in the new Bunch. Defaults to None. exclude (Optional[Union[Sequence[Any], Any]]): item(s) to exclude in the new Bunch. Defaults to None. """ pass """ Dunder Methods """ def __add__(self, other: Any) -> None: """Combines argument with 'contents' using the 'add' method. Args: other (Any): item to add to 'contents' using the 'add' method. """ self.add(item = other) return def __iadd__(self, other: Any) -> None: """Combines argument with 'contents' using the 'add' method. Args: other (Any): item to add to 'contents' using the 'add' method. """ self.add(item = other) return def __iter__(self) -> Iterator[Any]: """Returns iterable of 'contents'. Returns: Iterator: of 'contents'. """ return iter(self.contents) def __len__(self) -> int: """Returns length of 'contents'. Returns: int: length of 'contents'. """ return len(self.contents) # def __str__(self) -> str: # """Returns prettier str representation of an instance. # Returns: # str: a formatted str of an instance. # """ # return amos.recap.beautify(item = self, package = 'bunches')
(self, other)
10,637
bunches.base
__iadd__
Combines argument with 'contents' using the 'add' method. Args: other (Any): item to add to 'contents' using the 'add' method.
def __iadd__(self, other: Any) -> None: """Combines argument with 'contents' using the 'add' method. Args: other (Any): item to add to 'contents' using the 'add' method. """ self.add(item = other) return
(self, other: Any) -> NoneType
10,639
bunches.base
__iter__
Returns iterable of 'contents'. Returns: Iterator: of 'contents'.
def __iter__(self) -> Iterator[Any]: """Returns iterable of 'contents'. Returns: Iterator: of 'contents'. """ return iter(self.contents)
(self) -> collections.abc.Iterator[typing.Any]
10,640
bunches.base
__len__
Returns length of 'contents'. Returns: int: length of 'contents'.
def __len__(self) -> int: """Returns length of 'contents'. Returns: int: length of 'contents'. """ return len(self.contents)
(self) -> int
10,641
bunches.base
__repr__
null
def __iadd__(self, other: Any) -> None: """Combines argument with 'contents' using the 'add' method. Args: other (Any): item to add to 'contents' using the 'add' method. """ self.add(item = other) return
(self)
10,642
bunches.base
add
Adds 'item' to 'contents'. Args: item (Any): item to add to 'contents'.
@abc.abstractmethod def add(self, item: Any, *args: Any, **kwargs: Any) -> None: """Adds 'item' to 'contents'. Args: item (Any): item to add to 'contents'. """ pass
(self, item: Any, *args: Any, **kwargs: Any) -> NoneType
10,643
bunches.base
subset
Returns a subclass with some items removed from 'contents'. Args: include (Optional[Union[Sequence[Any], Any]]): item(s) to include in the new Bunch. Defaults to None. exclude (Optional[Union[Sequence[Any], Any]]): item(s) to exclude in the new Bunch. Defaults to None.
@abc.abstractmethod def subset( self, include: Optional[Union[Sequence[Any], Any]] = None, exclude: Optional[Union[Sequence[Any], Any]] = None, *args: Any, **kwargs: Any) -> Bunch: """Returns a subclass with some items removed from 'contents'. Args: include (Optional[Union[Sequence[Any], Any]]): item(s) to include in the new Bunch. Defaults to None. exclude (Optional[Union[Sequence[Any], Any]]): item(s) to exclude in the new Bunch. Defaults to None. """ pass
(self, include: Union[collections.abc.Sequence[Any], Any, NoneType] = None, exclude: Union[collections.abc.Sequence[Any], Any, NoneType] = None, *args: Any, **kwargs: Any) -> bunches.base.Bunch
10,644
bunches.mappings
Catalog
Wildcard and list-accepting dictionary. A Catalog inherits the differences between a Dictionary and an ordinary python dict. A Catalog differs from a Dictionary in 5 significant ways: 1) It recognizes an 'all' key which will return a list of all values stored in a Catalog instance. 2) It recognizes a 'default' key which will return all values matching keys listed in the 'default' attribute. 'default' can also be set using the 'catalog['default'] = new_default' assignment. If 'default' is not passed when the instance is initialized, the initial value of 'default' is 'all'. 3) It recognizes a 'none' key which will return an empty list. 4) It supports a list of keys being accessed with the matching values returned. For example, 'catalog[['first_key', 'second_key']]' will return the values for those keys in a list ['first_value', 'second_value']. 5) If a single key is sought, a Catalog can either return the stored value or a stored value in a list (if 'always_return_list' is True). The latter option is available to make iteration easier when the iterator assumes a single type will be returned. Args: contents (Mapping[Hashable, Any]]): stored dictionary. Defaults to an empty dict. default_factory (Any): default value to return when the 'get' method is used. default (Sequence[Any]]): a list of keys in 'contents' which will be used to return items when 'default' is sought. If not passed, 'default' will be set to all keys. always_return_list (bool): whether to return a list even when the key passed is not a list or special access key (True) or to return a list only when a list or special access key is used (False). Defaults to False.
class Catalog(Dictionary): """Wildcard and list-accepting dictionary. A Catalog inherits the differences between a Dictionary and an ordinary python dict. A Catalog differs from a Dictionary in 5 significant ways: 1) It recognizes an 'all' key which will return a list of all values stored in a Catalog instance. 2) It recognizes a 'default' key which will return all values matching keys listed in the 'default' attribute. 'default' can also be set using the 'catalog['default'] = new_default' assignment. If 'default' is not passed when the instance is initialized, the initial value of 'default' is 'all'. 3) It recognizes a 'none' key which will return an empty list. 4) It supports a list of keys being accessed with the matching values returned. For example, 'catalog[['first_key', 'second_key']]' will return the values for those keys in a list ['first_value', 'second_value']. 5) If a single key is sought, a Catalog can either return the stored value or a stored value in a list (if 'always_return_list' is True). The latter option is available to make iteration easier when the iterator assumes a single type will be returned. Args: contents (Mapping[Hashable, Any]]): stored dictionary. Defaults to an empty dict. default_factory (Any): default value to return when the 'get' method is used. default (Sequence[Any]]): a list of keys in 'contents' which will be used to return items when 'default' is sought. If not passed, 'default' will be set to all keys. always_return_list (bool): whether to return a list even when the key passed is not a list or special access key (True) or to return a list only when a list or special access key is used (False). Defaults to False. """ contents: Mapping[Hashable, Any] = dataclasses.field( default_factory = dict) default_factory: Optional[Any] = None default: Optional[Any] = 'all' always_return_list: bool = False """ Dunder Methods """ def __getitem__( self, key: Union[Hashable, Sequence[Hashable]]) -> Union[Any, Sequence[Any]]: """Returns value(s) for 'key' in 'contents'. The method searches for 'all', 'default', and 'none' matching wildcard options before searching for direct matches in 'contents'. Args: key (Union[Hashable, Sequence[Hashable]]): key(s) in 'contents'. Returns: Union[Any, Sequence[Any]]: value(s) stored in 'contents'. """ # Returns a list of all values if the 'all' key is sought. if key in _ALL_KEYS: return list(self.contents.values()) # Returns a list of values for keys listed in 'default' attribute. elif key in _DEFAULT_KEYS: return self[self.default] # Returns an empty list if a null value is sought. elif key in _NONE_KEYS: if self.default_factory is None: if self.always_return_list: return [] else: return None else: try: return self.default_factory() except TypeError: return self.default_factory # Returns list of matching values if 'key' is list-like. elif isinstance(key, Sequence) and not isinstance(key, str): return [self.contents[k] for k in key if k in self.contents] # Returns matching value if key is not a non-str Sequence or wildcard. else: try: if self.always_return_list: return [self.contents[key]] else: return self.contents[key] except KeyError: raise KeyError(f'{key} is not in {self.__class__.__name__}') def __setitem__( self, key: Union[Hashable, Sequence[Hashable]], value: Union[Any, Sequence[Any]]) -> None: """sets 'key' in 'contents' to 'value'. Args: key (Union[Hashable, Sequence[Hashable]]): key(s) to set in 'contents'. value (Union[Any, Sequence[Any]]): value(s) to be paired with 'key' in 'contents'. """ try: self.contents[key] = value except TypeError: self.contents.update(dict(zip(key, value))) # type: ignore return def __delitem__(self, key: Union[Hashable, Sequence[Hashable]]) -> None: """Deletes 'key' in 'contents'. Args: key (Union[Hashable, Sequence[Hashable]]): name(s) of key(s) in 'contents' to delete the key/value pair. """ keys = list(utilities.iterify(item = key)) if all(k in self for k in keys): self.contents = { i: self.contents[i] for i in self.contents if i not in keys} else: raise KeyError(f'{key} not found in the Catalog') return
(contents: collections.abc.Mapping[collections.abc.Hashable, typing.Any] = <factory>, default_factory: Optional[Any] = None, default: Optional[Any] = 'all', always_return_list: bool = False) -> None
10,647
bunches.mappings
__delitem__
Deletes 'key' in 'contents'. Args: key (Union[Hashable, Sequence[Hashable]]): name(s) of key(s) in 'contents' to delete the key/value pair.
def __delitem__(self, key: Union[Hashable, Sequence[Hashable]]) -> None: """Deletes 'key' in 'contents'. Args: key (Union[Hashable, Sequence[Hashable]]): name(s) of key(s) in 'contents' to delete the key/value pair. """ keys = list(utilities.iterify(item = key)) if all(k in self for k in keys): self.contents = { i: self.contents[i] for i in self.contents if i not in keys} else: raise KeyError(f'{key} not found in the Catalog') return
(self, key: Union[collections.abc.Hashable, collections.abc.Sequence[collections.abc.Hashable]]) -> NoneType
10,648
bunches.mappings
__eq__
null
""" mappings: extensible, flexible, lightweight dict-like classes Corey Rayburn Yung <[email protected]> Copyright 2021, Corey Rayburn Yung License: Apache-2.0 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. Contents: Dictionary (Bunch, MutableMapping): bunches's drop-in replacement for a python dict with some added functionality. Catalog (Dictionary): wildcard-accepting dict which is primarily intended for storing different options and strategies. It also returns lists of matches if a list of keys is provided. ToDo: """ from __future__ import annotations from collections.abc import Hashable, Iterator, Mapping, MutableMapping, Sequence import copy import dataclasses import inspect from typing import Any, Optional, Type, Union from . import base from . import utilities _ALL_KEYS: list[Any] = ['all', 'All', ['all'], ['All']] _DEFAULT_KEYS: list[Any] = [ 'default', 'defaults', 'Default', 'Defaults', ['default'], ['defaults'], ['Default'], ['Defaults']] _NONE_KEYS: list[Any] = ['none', 'None', ['none'], ['None']] @dataclasses.dataclass # type: ignore class Dictionary(base.Bunch, MutableMapping): # type: ignore """Basic bunches dict replacement. A Dictionary differs from an ordinary python dict in ways inherited from Bunch by requiring 'add' and 'subset' methods, storing data in 'contents', and allowing the '+' operator to join Dictionary instances with other mappings, including Dictionary instances. # In addition, it differs in 1 other significant way: # 1) When returning 'keys', 'values' and 'items', this class returns them # as tuples instead of KeysView, ValuesView, and ItemsView. Args: contents (MutableMapping[Hashable, Any]): stored dictionary. Defaults to an empty dict. default_factory (Optional[Any]): default value to return or default function to call when the 'get' method is used. Defaults to None. """ contents: MutableMapping[Hashable, Any] = dataclasses.field( default_factory = dict) default_factory: Optional[Any] = None """ Public Methods """ def add(self, item: Mapping[Hashable, Any], **kwargs: Any) -> None: """Adds 'item' to the 'contents' attribute. Args: item (Mapping[Hashable, Any]): items to add to 'contents' attribute. kwargs: creates a consistent interface even when subclasses have additional parameters. """ self.contents.update(item, **kwargs) return @classmethod def fromkeys( cls, keys: Sequence[Hashable], value: Any, **kwargs: Any) -> Dictionary: """Emulates the 'fromkeys' class method from a python dict. Args: keys (Sequence[Hashable]): items to be keys in a new Dictionary. value (Any): the value to use for all values in a new Dictionary. Returns: Dictionary: formed from 'keys' and 'value'. """ return cls(contents = dict.fromkeys(keys, value), **kwargs) def get(self, key: Hashable, default: Optional[Any] = None) -> Any: # type: ignore """Returns value in 'contents' or default options. Args: key (Hashable): key for value in 'contents'. default (Optional[Any]): default value to return if 'key' is not found in 'contents'. Raises: KeyError: if 'key' is not in the Dictionary and 'default' and the 'default_factory' attribute are both None. Returns: Any: value matching key in 'contents' or 'default_factory' value. """ try: return self[key] except (KeyError, TypeError): if default is None: if self.default_factory is None: raise KeyError(f'{key} is not in the Dictionary') else: try: return self.default_factory() except TypeError: return self.default_factory else: return default # def items(self) -> tuple[tuple[Hashable, Any], ...]: # type: ignore # """Emulates python dict 'items' method. # Returns: # tuple[tuple[Hashable], Any]: a tuple equivalent to dict.items(). # """ # return tuple(zip(self.keys(), self.values())) # def keys(self) -> tuple[Hashable, ...]: # type: ignore # """Returns 'contents' keys as a tuple. # Returns: # tuple[Hashable, ...]: a tuple equivalent to dict.keys(). # """ # return tuple(self.contents.keys()) def setdefault(self, value: Any) -> None: # type: ignore """sets default value to return when 'get' method is used. Args: value (Any): default value to return when 'get' is called and the 'default' parameter to 'get' is None. """ self.default_factory = value return def subset( self, include: Optional[Union[Hashable, Sequence[Hashable]]] = None, exclude: Optional[Union[Hashable, Sequence[Hashable]]] = None) -> ( Dictionary): """Returns a new instance with a subset of 'contents'. This method applies 'include' before 'exclude' if both are passed. If 'include' is None, all existing keys will be added before 'exclude' is applied. Args: include (Optional[Union[Hashable, Sequence[Hashable]]]): key(s) to include in the new Dictionary instance. exclude (Optional[Union[Hashable, Sequence[Hashable]]]): key(s) to exclude in the new Dictionary instance. Raises: ValueError: if 'include' and 'exclude' are both None. Returns: Dictionary: with only keys from 'include' and no keys in 'exclude'. """ if include is None and exclude is None: raise ValueError('include or exclude must not be None') else: if include is None: contents = self.contents else: include = list(utilities.iterify(item = include)) contents = {k: self.contents[k] for k in include} if exclude is not None: exclude = list(utilities.iterify(item = exclude)) contents = { k: v for k, v in contents.items() if k not in exclude} new_dictionary = copy.deepcopy(self) new_dictionary.contents = contents return new_dictionary # def values(self) -> tuple[Any, ...]: # type: ignore # """Returns 'contents' values as a tuple. # Returns: # tuple[Any, ...]: a tuple equivalent to dict.values(). # """ # return tuple(self.contents.values()) """ Dunder Methods """ def __getitem__(self, key: Hashable) -> Any: """Returns value for 'key' in 'contents'. Args: key (Hashable): key in 'contents' for which a value is sought. Returns: Any: value stored in 'contents'. """ return self.contents[key] def __setitem__(self, key: Hashable, value: Any) -> None: """sets 'key' in 'contents' to 'value'. Args: key (Hashable): key to set in 'contents'. value (Any): value to be paired with 'key' in 'contents'. """ self.contents[key] = value return def __delitem__(self, key: Hashable) -> None: """Deletes 'key' in 'contents'. Args: key (Hashable): key in 'contents' to delete the key/value pair. """ del self.contents[key] return
(self, other)
10,649
bunches.mappings
__getitem__
Returns value(s) for 'key' in 'contents'. The method searches for 'all', 'default', and 'none' matching wildcard options before searching for direct matches in 'contents'. Args: key (Union[Hashable, Sequence[Hashable]]): key(s) in 'contents'. Returns: Union[Any, Sequence[Any]]: value(s) stored in 'contents'.
def __getitem__( self, key: Union[Hashable, Sequence[Hashable]]) -> Union[Any, Sequence[Any]]: """Returns value(s) for 'key' in 'contents'. The method searches for 'all', 'default', and 'none' matching wildcard options before searching for direct matches in 'contents'. Args: key (Union[Hashable, Sequence[Hashable]]): key(s) in 'contents'. Returns: Union[Any, Sequence[Any]]: value(s) stored in 'contents'. """ # Returns a list of all values if the 'all' key is sought. if key in _ALL_KEYS: return list(self.contents.values()) # Returns a list of values for keys listed in 'default' attribute. elif key in _DEFAULT_KEYS: return self[self.default] # Returns an empty list if a null value is sought. elif key in _NONE_KEYS: if self.default_factory is None: if self.always_return_list: return [] else: return None else: try: return self.default_factory() except TypeError: return self.default_factory # Returns list of matching values if 'key' is list-like. elif isinstance(key, Sequence) and not isinstance(key, str): return [self.contents[k] for k in key if k in self.contents] # Returns matching value if key is not a non-str Sequence or wildcard. else: try: if self.always_return_list: return [self.contents[key]] else: return self.contents[key] except KeyError: raise KeyError(f'{key} is not in {self.__class__.__name__}')
(self, key: Union[collections.abc.Hashable, collections.abc.Sequence[collections.abc.Hashable]]) -> Union[Any, collections.abc.Sequence[Any]]
10,654
bunches.mappings
__repr__
null
def __setitem__(self, key: Hashable, value: Any) -> None: """sets 'key' in 'contents' to 'value'. Args: key (Hashable): key to set in 'contents'. value (Any): value to be paired with 'key' in 'contents'. """ self.contents[key] = value return
(self)
10,655
bunches.mappings
__setitem__
sets 'key' in 'contents' to 'value'. Args: key (Union[Hashable, Sequence[Hashable]]): key(s) to set in 'contents'. value (Union[Any, Sequence[Any]]): value(s) to be paired with 'key' in 'contents'.
def __setitem__( self, key: Union[Hashable, Sequence[Hashable]], value: Union[Any, Sequence[Any]]) -> None: """sets 'key' in 'contents' to 'value'. Args: key (Union[Hashable, Sequence[Hashable]]): key(s) to set in 'contents'. value (Union[Any, Sequence[Any]]): value(s) to be paired with 'key' in 'contents'. """ try: self.contents[key] = value except TypeError: self.contents.update(dict(zip(key, value))) # type: ignore return
(self, key: Union[collections.abc.Hashable, collections.abc.Sequence[collections.abc.Hashable]], value: Union[Any, collections.abc.Sequence[Any]]) -> NoneType
10,656
bunches.mappings
add
Adds 'item' to the 'contents' attribute. Args: item (Mapping[Hashable, Any]): items to add to 'contents' attribute. kwargs: creates a consistent interface even when subclasses have additional parameters.
def add(self, item: Mapping[Hashable, Any], **kwargs: Any) -> None: """Adds 'item' to the 'contents' attribute. Args: item (Mapping[Hashable, Any]): items to add to 'contents' attribute. kwargs: creates a consistent interface even when subclasses have additional parameters. """ self.contents.update(item, **kwargs) return
(self, item: collections.abc.Mapping[collections.abc.Hashable, typing.Any], **kwargs: Any) -> NoneType
10,658
bunches.mappings
get
Returns value in 'contents' or default options. Args: key (Hashable): key for value in 'contents'. default (Optional[Any]): default value to return if 'key' is not found in 'contents'. Raises: KeyError: if 'key' is not in the Dictionary and 'default' and the 'default_factory' attribute are both None. Returns: Any: value matching key in 'contents' or 'default_factory' value.
def get(self, key: Hashable, default: Optional[Any] = None) -> Any: # type: ignore """Returns value in 'contents' or default options. Args: key (Hashable): key for value in 'contents'. default (Optional[Any]): default value to return if 'key' is not found in 'contents'. Raises: KeyError: if 'key' is not in the Dictionary and 'default' and the 'default_factory' attribute are both None. Returns: Any: value matching key in 'contents' or 'default_factory' value. """ try: return self[key] except (KeyError, TypeError): if default is None: if self.default_factory is None: raise KeyError(f'{key} is not in the Dictionary') else: try: return self.default_factory() except TypeError: return self.default_factory else: return default
(self, key: collections.abc.Hashable, default: Optional[Any] = None) -> Any
10,663
bunches.mappings
setdefault
sets default value to return when 'get' method is used. Args: value (Any): default value to return when 'get' is called and the 'default' parameter to 'get' is None.
def setdefault(self, value: Any) -> None: # type: ignore """sets default value to return when 'get' method is used. Args: value (Any): default value to return when 'get' is called and the 'default' parameter to 'get' is None. """ self.default_factory = value return
(self, value: Any) -> NoneType
10,664
bunches.mappings
subset
Returns a new instance with a subset of 'contents'. This method applies 'include' before 'exclude' if both are passed. If 'include' is None, all existing keys will be added before 'exclude' is applied. Args: include (Optional[Union[Hashable, Sequence[Hashable]]]): key(s) to include in the new Dictionary instance. exclude (Optional[Union[Hashable, Sequence[Hashable]]]): key(s) to exclude in the new Dictionary instance. Raises: ValueError: if 'include' and 'exclude' are both None. Returns: Dictionary: with only keys from 'include' and no keys in 'exclude'.
def subset( self, include: Optional[Union[Hashable, Sequence[Hashable]]] = None, exclude: Optional[Union[Hashable, Sequence[Hashable]]] = None) -> ( Dictionary): """Returns a new instance with a subset of 'contents'. This method applies 'include' before 'exclude' if both are passed. If 'include' is None, all existing keys will be added before 'exclude' is applied. Args: include (Optional[Union[Hashable, Sequence[Hashable]]]): key(s) to include in the new Dictionary instance. exclude (Optional[Union[Hashable, Sequence[Hashable]]]): key(s) to exclude in the new Dictionary instance. Raises: ValueError: if 'include' and 'exclude' are both None. Returns: Dictionary: with only keys from 'include' and no keys in 'exclude'. """ if include is None and exclude is None: raise ValueError('include or exclude must not be None') else: if include is None: contents = self.contents else: include = list(utilities.iterify(item = include)) contents = {k: self.contents[k] for k in include} if exclude is not None: exclude = list(utilities.iterify(item = exclude)) contents = { k: v for k, v in contents.items() if k not in exclude} new_dictionary = copy.deepcopy(self) new_dictionary.contents = contents return new_dictionary
(self, include: Union[collections.abc.Hashable, collections.abc.Sequence[collections.abc.Hashable], NoneType] = None, exclude: Union[collections.abc.Hashable, collections.abc.Sequence[collections.abc.Hashable], NoneType] = None) -> bunches.mappings.Dictionary
10,667
collections.abc
Collection
null
from collections.abc import Collection
()
10,671
collections.abc
Container
null
from collections.abc import Container
()
10,673
bunches.mappings
Dictionary
Basic bunches dict replacement. A Dictionary differs from an ordinary python dict in ways inherited from Bunch by requiring 'add' and 'subset' methods, storing data in 'contents', and allowing the '+' operator to join Dictionary instances with other mappings, including Dictionary instances. # In addition, it differs in 1 other significant way: # 1) When returning 'keys', 'values' and 'items', this class returns them # as tuples instead of KeysView, ValuesView, and ItemsView. Args: contents (MutableMapping[Hashable, Any]): stored dictionary. Defaults to an empty dict. default_factory (Optional[Any]): default value to return or default function to call when the 'get' method is used. Defaults to None.
class Dictionary(base.Bunch, MutableMapping): # type: ignore """Basic bunches dict replacement. A Dictionary differs from an ordinary python dict in ways inherited from Bunch by requiring 'add' and 'subset' methods, storing data in 'contents', and allowing the '+' operator to join Dictionary instances with other mappings, including Dictionary instances. # In addition, it differs in 1 other significant way: # 1) When returning 'keys', 'values' and 'items', this class returns them # as tuples instead of KeysView, ValuesView, and ItemsView. Args: contents (MutableMapping[Hashable, Any]): stored dictionary. Defaults to an empty dict. default_factory (Optional[Any]): default value to return or default function to call when the 'get' method is used. Defaults to None. """ contents: MutableMapping[Hashable, Any] = dataclasses.field( default_factory = dict) default_factory: Optional[Any] = None """ Public Methods """ def add(self, item: Mapping[Hashable, Any], **kwargs: Any) -> None: """Adds 'item' to the 'contents' attribute. Args: item (Mapping[Hashable, Any]): items to add to 'contents' attribute. kwargs: creates a consistent interface even when subclasses have additional parameters. """ self.contents.update(item, **kwargs) return @classmethod def fromkeys( cls, keys: Sequence[Hashable], value: Any, **kwargs: Any) -> Dictionary: """Emulates the 'fromkeys' class method from a python dict. Args: keys (Sequence[Hashable]): items to be keys in a new Dictionary. value (Any): the value to use for all values in a new Dictionary. Returns: Dictionary: formed from 'keys' and 'value'. """ return cls(contents = dict.fromkeys(keys, value), **kwargs) def get(self, key: Hashable, default: Optional[Any] = None) -> Any: # type: ignore """Returns value in 'contents' or default options. Args: key (Hashable): key for value in 'contents'. default (Optional[Any]): default value to return if 'key' is not found in 'contents'. Raises: KeyError: if 'key' is not in the Dictionary and 'default' and the 'default_factory' attribute are both None. Returns: Any: value matching key in 'contents' or 'default_factory' value. """ try: return self[key] except (KeyError, TypeError): if default is None: if self.default_factory is None: raise KeyError(f'{key} is not in the Dictionary') else: try: return self.default_factory() except TypeError: return self.default_factory else: return default # def items(self) -> tuple[tuple[Hashable, Any], ...]: # type: ignore # """Emulates python dict 'items' method. # Returns: # tuple[tuple[Hashable], Any]: a tuple equivalent to dict.items(). # """ # return tuple(zip(self.keys(), self.values())) # def keys(self) -> tuple[Hashable, ...]: # type: ignore # """Returns 'contents' keys as a tuple. # Returns: # tuple[Hashable, ...]: a tuple equivalent to dict.keys(). # """ # return tuple(self.contents.keys()) def setdefault(self, value: Any) -> None: # type: ignore """sets default value to return when 'get' method is used. Args: value (Any): default value to return when 'get' is called and the 'default' parameter to 'get' is None. """ self.default_factory = value return def subset( self, include: Optional[Union[Hashable, Sequence[Hashable]]] = None, exclude: Optional[Union[Hashable, Sequence[Hashable]]] = None) -> ( Dictionary): """Returns a new instance with a subset of 'contents'. This method applies 'include' before 'exclude' if both are passed. If 'include' is None, all existing keys will be added before 'exclude' is applied. Args: include (Optional[Union[Hashable, Sequence[Hashable]]]): key(s) to include in the new Dictionary instance. exclude (Optional[Union[Hashable, Sequence[Hashable]]]): key(s) to exclude in the new Dictionary instance. Raises: ValueError: if 'include' and 'exclude' are both None. Returns: Dictionary: with only keys from 'include' and no keys in 'exclude'. """ if include is None and exclude is None: raise ValueError('include or exclude must not be None') else: if include is None: contents = self.contents else: include = list(utilities.iterify(item = include)) contents = {k: self.contents[k] for k in include} if exclude is not None: exclude = list(utilities.iterify(item = exclude)) contents = { k: v for k, v in contents.items() if k not in exclude} new_dictionary = copy.deepcopy(self) new_dictionary.contents = contents return new_dictionary # def values(self) -> tuple[Any, ...]: # type: ignore # """Returns 'contents' values as a tuple. # Returns: # tuple[Any, ...]: a tuple equivalent to dict.values(). # """ # return tuple(self.contents.values()) """ Dunder Methods """ def __getitem__(self, key: Hashable) -> Any: """Returns value for 'key' in 'contents'. Args: key (Hashable): key in 'contents' for which a value is sought. Returns: Any: value stored in 'contents'. """ return self.contents[key] def __setitem__(self, key: Hashable, value: Any) -> None: """sets 'key' in 'contents' to 'value'. Args: key (Hashable): key to set in 'contents'. value (Any): value to be paired with 'key' in 'contents'. """ self.contents[key] = value return def __delitem__(self, key: Hashable) -> None: """Deletes 'key' in 'contents'. Args: key (Hashable): key in 'contents' to delete the key/value pair. """ del self.contents[key] return
(contents: collections.abc.MutableMapping[collections.abc.Hashable, typing.Any] = <factory>, default_factory: Optional[Any] = None) -> None
10,676
bunches.mappings
__delitem__
Deletes 'key' in 'contents'. Args: key (Hashable): key in 'contents' to delete the key/value pair.
def __delitem__(self, key: Hashable) -> None: """Deletes 'key' in 'contents'. Args: key (Hashable): key in 'contents' to delete the key/value pair. """ del self.contents[key] return
(self, key: collections.abc.Hashable) -> NoneType
10,678
bunches.mappings
__getitem__
Returns value for 'key' in 'contents'. Args: key (Hashable): key in 'contents' for which a value is sought. Returns: Any: value stored in 'contents'.
def __getitem__(self, key: Hashable) -> Any: """Returns value for 'key' in 'contents'. Args: key (Hashable): key in 'contents' for which a value is sought. Returns: Any: value stored in 'contents'. """ return self.contents[key]
(self, key: collections.abc.Hashable) -> Any
10,684
bunches.mappings
__setitem__
sets 'key' in 'contents' to 'value'. Args: key (Hashable): key to set in 'contents'. value (Any): value to be paired with 'key' in 'contents'.
def __setitem__(self, key: Hashable, value: Any) -> None: """sets 'key' in 'contents' to 'value'. Args: key (Hashable): key to set in 'contents'. value (Any): value to be paired with 'key' in 'contents'. """ self.contents[key] = value return
(self, key: collections.abc.Hashable, value: Any) -> NoneType
10,696
collections.abc
Hashable
null
from collections.abc import Hashable
()
10,698
bunches.sequences
Hybrid
Iterable that has both a dict and list interfaces. Hybrid combines the functionality and interfaces of python dicts and lists. It allows duplicate keys and list-like iteration while supporting the easier access methods of dictionaries. In order to support this hybrid approach to iterables, Hybrid can only store items that are hashable or have a 'name' attribute or property that contains or returns a hashable value. A Hybrid inherits the differences between a Listing and an ordinary python list. A Hybrid differs from a Listing in 3 significant ways: 1) It only stores hashable items or objects for which a str name can be derived (using the get_name function). 2) Hybrid has an interface of both a dict and a list, but stores a list. Hybrid does this by taking advantage of the 'name' attribute or hashability of stored items. A 'name' or hash acts as a key to create the facade of a dict with the items in the stored list serving as values. This allows for duplicate keys for storing items, simpler iteration than a dict, and support for returning multiple matching items. This design comes at the expense of lookup speed. As a result, Hybrid should only be used if a high volume of access calls is not anticipated. Ordinarily, the loss of lookup speed should have negligible effect on overall performance. 3) Hybrids should not store int types. This ensures that when, for example, a 'hybrid[3]' is called, the item at that index is returned. If int types are stored, that call would create uncertainty as to whether an index or item should be returned. By design, int types are assumed to be calls to return the item at that index. 4) When using dict access methods, a list of matches may be returned because a Hybrid allows duplicate pseudo-keys to be used. Args: contents (MutableSequence[Hashable]): items to store that are hashable or have a 'name' attribute. Defaults to an empty list. default_factory (Optional[Any]): default value to return or default function to call when the 'get' method is used. Defaults to None.
class Hybrid(Listing): """Iterable that has both a dict and list interfaces. Hybrid combines the functionality and interfaces of python dicts and lists. It allows duplicate keys and list-like iteration while supporting the easier access methods of dictionaries. In order to support this hybrid approach to iterables, Hybrid can only store items that are hashable or have a 'name' attribute or property that contains or returns a hashable value. A Hybrid inherits the differences between a Listing and an ordinary python list. A Hybrid differs from a Listing in 3 significant ways: 1) It only stores hashable items or objects for which a str name can be derived (using the get_name function). 2) Hybrid has an interface of both a dict and a list, but stores a list. Hybrid does this by taking advantage of the 'name' attribute or hashability of stored items. A 'name' or hash acts as a key to create the facade of a dict with the items in the stored list serving as values. This allows for duplicate keys for storing items, simpler iteration than a dict, and support for returning multiple matching items. This design comes at the expense of lookup speed. As a result, Hybrid should only be used if a high volume of access calls is not anticipated. Ordinarily, the loss of lookup speed should have negligible effect on overall performance. 3) Hybrids should not store int types. This ensures that when, for example, a 'hybrid[3]' is called, the item at that index is returned. If int types are stored, that call would create uncertainty as to whether an index or item should be returned. By design, int types are assumed to be calls to return the item at that index. 4) When using dict access methods, a list of matches may be returned because a Hybrid allows duplicate pseudo-keys to be used. Args: contents (MutableSequence[Hashable]): items to store that are hashable or have a 'name' attribute. Defaults to an empty list. default_factory (Optional[Any]): default value to return or default function to call when the 'get' method is used. Defaults to None. """ contents: MutableSequence[Hashable] = dataclasses.field( default_factory = list) default_factory: Optional[Any] = None """ Public Methods """ def get(self, key: Hashable, default: Optional[Any] = None) -> Any: # type: ignore """Returns value in 'contents' or default options. Args: key (Hashable): key for value in 'contents'. default (Optional[Any]): default value to return if 'key' is not found in 'contents'. Raises: KeyError: if 'key' is not in the Hybrid and 'default' and the 'default_factory' attribute are both None. Returns: Any: value matching key in 'contents' or 'default_factory' value. """ try: return self[key] except (KeyError, TypeError): if default is None: if self.default_factory is None: raise KeyError(f'{key} is not in the Hybrid') else: try: return self.default_factory() except TypeError: return self.default_factory else: return default def items(self) -> tuple[tuple[Hashable, ...], tuple[Any, ...]]: """Emulates python dict 'items' method. Returns: tuple[tuple[Hashable, ...], tuple[Any, ...]]: a tuple equivalent to dict.items(). A Hybrid cannot actually create an ItemsView because that would eliminate any duplicate keys, which are permitted by Hybrid. """ return tuple(zip(self.keys(), self.values())) def keys(self) -> tuple[Hashable, ...]: """Emulates python dict 'keys' method. Returns: tuple[Hashable, ...]: a tuple equivalent to dict.keys(). A Hybrid cannot actually create an KeysView because that would eliminate any duplicate keys, which are permitted by Hybrid. """ return tuple([utilities.get_name(item = c) for c in self.contents]) def setdefault(self, value: Any) -> None: # type: ignore """sets default value to return when 'get' method is used. Args: value (Any): default value to return. """ self.default_factory = value return def update(self, items: Mapping[Any, Any]) -> None: """Mimics the dict 'update' method by extending 'contents' with 'items'. Args: items (Mapping[Any, Any]): items to add to the 'contents' attribute. The values of 'items' are added to 'contents' and the keys become the 'name' attributes of those values. As a result, the keys of 'items' are discarded. To mimic dict' update', the passed 'items' values are added to 'contents' by the 'extend' method which adds the values to the end of 'contents'. """ self.extend(list(items.values())) return def values(self) -> tuple[Any, ...]: """Emulates python dict 'values' method. Returns: tuple[Any, ...]: a tuple equivalent to dict.values(). A Hybrid cannot actually create an ValuesView because that would eliminate any duplicate keys, which are permitted by Hybrid. """ return tuple(self.contents) """ Dunder Methods """ def __getitem__(self, key: Union[Hashable, int]) -> Any: # type: ignore """Returns value(s) for 'key' in 'contents'. If 'key' is not an int type, this method looks for a matching 'name' attribute in the stored instances. If 'key' is an int type, this method returns the stored item at the corresponding index. If only one match is found, a single item is returned. If more are found, a Hybrid or Hybrid subclass with the matching 'name' attributes is returned. Args: key (Union[Hashable, int]): name of an item or index to search for in 'contents'. Returns: Any: value(s) stored in 'contents' that correspond to 'key'. If there is more than one match, the return is a Hybrid or Hybrid subclass with that matching stored items. """ if isinstance(key, int): return self.contents[key] else: matches = [ c for c in self.contents if utilities.get_name(item = c) == key] # matches = [] # for value in self.contents: # if ( # hash(value) == key # or utilities.get_name(item = value) == key): # matches.append(value) # matches = [ # i for i, c in enumerate(self.contents) # if utilities.get_name(c) == key] if len(matches) == 0: raise KeyError(f'{key} is not in {self.__class__.__name__}') elif len(matches) == 1: return matches[0] else: return matches def __setitem__(self, key: Union[Any, int], value: Any) -> None: """sets 'key' in 'contents' to 'value'. Args: key (Union[Any, int]): if key isn't an int, it is ignored (since the 'name' attribute of the value will be acting as the key). In such a case, the 'value' is added to the end of 'contents'. If key is an int, 'value' is assigned at the that index number in 'contents'. value (Any): value to be paired with 'key' in 'contents'. """ if isinstance(key, int): self.contents[key] = value else: self.add(value) return def __delitem__(self, key: Union[Any, int]) -> None: """Deletes item matching 'key' in 'contents'. If 'key' is not an int type, this method looks for a matching 'name' attribute in the stored instances and deletes all such items. If 'key' is an int type, only the item at that index is deleted. Args: key (Union[Any, int]): name or index in 'contents' to delete. """ if isinstance(key, int): del self.contents[key] else: self.contents = [ c for c in self.contents if utilities.get_name(c) != key] return
(contents: collections.abc.MutableSequence[collections.abc.Hashable] = <factory>, default_factory: Optional[Any] = None) -> None
10,701
bunches.sequences
__delitem__
Deletes item matching 'key' in 'contents'. If 'key' is not an int type, this method looks for a matching 'name' attribute in the stored instances and deletes all such items. If 'key' is an int type, only the item at that index is deleted. Args: key (Union[Any, int]): name or index in 'contents' to delete.
def __delitem__(self, key: Union[Any, int]) -> None: """Deletes item matching 'key' in 'contents'. If 'key' is not an int type, this method looks for a matching 'name' attribute in the stored instances and deletes all such items. If 'key' is an int type, only the item at that index is deleted. Args: key (Union[Any, int]): name or index in 'contents' to delete. """ if isinstance(key, int): del self.contents[key] else: self.contents = [ c for c in self.contents if utilities.get_name(c) != key] return
(self, key: Union[Any, int]) -> NoneType
10,702
bunches.sequences
__eq__
null
""" sequences: extensible, flexible, lightweight list-like classes Corey Rayburn Yung <[email protected]> Copyright 2021, Corey Rayburn Yung License: Apache-2.0 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. Contents: Listing (Bunch, MutableSequence): drop-in replacement for a python list with additional functionality. Hybrid (Listing): iterable with both dict and list interfaces. Stored items must be hashable or have a 'name' attribute. ToDo: """ from __future__ import annotations from collections.abc import Hashable, Mapping, MutableSequence, Sequence import copy import dataclasses from typing import Any, Optional, Union from . import base from . import utilities @dataclasses.dataclass # type: ignore class Listing(base.Bunch, MutableSequence): # type: ignore """Basic bunches list replacement. A Listing differs from an ordinary python list in ways required by inheriting from Bunch: 'add' and 'subset' methods, storing data in 'contents', and allowing the '+' operator to join Listings with other lists and Listings) and in 1 other way. 1) It includes a 'prepend' method for adding one or more items to the beginning of the stored list. The 'add' method attempts to extend 'contents' with the item to be added. If this fails, it appends the item to 'contents'. Args: contents (MutableSequence[Any]): items to store in a list. Defaults to an empty list. """ contents: MutableSequence[Any] = dataclasses.field(default_factory = list) """ Public Methods """ def add(self, item: Union[Any, Sequence[Any]]) -> None: """Tries to extend 'contents' with 'item'. Otherwise, it appends. The method will extend all passed sequences, except str types, which it will append. Args: item (Union[Any, Sequence[Any]]): item(s) to add to the 'contents' attribute. """ if isinstance(item, Sequence) and not isinstance(item, str): self.contents.extend(item) else: self.contents.append(item) return def insert(self, index: int, item: Any) -> None: """Inserts 'item' at 'index' in 'contents'. Args: index (int): index to insert 'item' at. item (Any): object to be inserted. """ self.contents.insert(index, item) return def prepend(self, item: Union[Any, Sequence[Any]]) -> None: """Prepends 'item' to 'contents'. If 'item' is a non-str sequence, 'prepend' adds its contents to the stored list in the order they appear in 'item'. Args: item (Union[Any, Sequence[Any]]): item(s) to prepend to the 'contents' attribute. """ if isinstance(item, Sequence) and not isinstance(item, str): for thing in reversed(item): self.prepend(item = thing) else: self.insert(0, item) return def subset( self, include: Optional[Union[Sequence[Any], Any]] = None, exclude: Optional[Union[Sequence[Any], Any]] = None) -> Listing: """Returns a new instance with a subset of 'contents'. This method applies 'include' before 'exclude' if both are passed. If 'include' is None, all existing keys will be added before 'exclude' is applied. Args: include (Optional[Union[Sequence[Any], Any]]): item(s) to include in the new instance. Defaults to None. exclude (Optional[Union[Sequence[Any], Any]]): item(s) to exclude in the new instance. Defaults to None. Raises: ValueError: if 'include' and 'exclude' are both None. Returns: Listing: with only items from 'include' and no items in 'exclude'. """ if include is None and exclude is None: raise ValueError('include or exclude must not be None') else: if include is None: contents = self.contents else: include = list(utilities.iterify(item = include)) contents = [i for i in self.contents if i in include] if exclude is not None: exclude = list(utilities.iterify(item = exclude)) contents = [i for i in contents if i not in exclude] new_listing = copy.deepcopy(self) new_listing.contents = contents return new_listing """ Dunder Methods """ def __getitem__(self, index: Any) -> Any: """Returns value(s) for 'key' in 'contents'. Args: index (Any): index to search for in 'contents'. Returns: Any: item stored in 'contents' at key. """ return self.contents[index] def __setitem__(self, index: Any, value: Any) -> None: """sets 'key' in 'contents' to 'value'. Args: index (Any): index to set 'value' to in 'contents'. value (Any): value to be set at 'key' in 'contents'. """ self.contents[index] = value return def __delitem__(self, index: Any) -> None: """Deletes item at 'key' index in 'contents'. Args: index (Any): index in 'contents' to delete. """ del self.contents[index] return
(self, other)
10,703
bunches.sequences
__getitem__
Returns value(s) for 'key' in 'contents'. If 'key' is not an int type, this method looks for a matching 'name' attribute in the stored instances. If 'key' is an int type, this method returns the stored item at the corresponding index. If only one match is found, a single item is returned. If more are found, a Hybrid or Hybrid subclass with the matching 'name' attributes is returned. Args: key (Union[Hashable, int]): name of an item or index to search for in 'contents'. Returns: Any: value(s) stored in 'contents' that correspond to 'key'. If there is more than one match, the return is a Hybrid or Hybrid subclass with that matching stored items.
def __getitem__(self, key: Union[Hashable, int]) -> Any: # type: ignore """Returns value(s) for 'key' in 'contents'. If 'key' is not an int type, this method looks for a matching 'name' attribute in the stored instances. If 'key' is an int type, this method returns the stored item at the corresponding index. If only one match is found, a single item is returned. If more are found, a Hybrid or Hybrid subclass with the matching 'name' attributes is returned. Args: key (Union[Hashable, int]): name of an item or index to search for in 'contents'. Returns: Any: value(s) stored in 'contents' that correspond to 'key'. If there is more than one match, the return is a Hybrid or Hybrid subclass with that matching stored items. """ if isinstance(key, int): return self.contents[key] else: matches = [ c for c in self.contents if utilities.get_name(item = c) == key] # matches = [] # for value in self.contents: # if ( # hash(value) == key # or utilities.get_name(item = value) == key): # matches.append(value) # matches = [ # i for i, c in enumerate(self.contents) # if utilities.get_name(c) == key] if len(matches) == 0: raise KeyError(f'{key} is not in {self.__class__.__name__}') elif len(matches) == 1: return matches[0] else: return matches
(self, key: Union[collections.abc.Hashable, int]) -> Any
10,708
bunches.sequences
__repr__
null
def get(self, key: Hashable, default: Optional[Any] = None) -> Any: # type: ignore """Returns value in 'contents' or default options. Args: key (Hashable): key for value in 'contents'. default (Optional[Any]): default value to return if 'key' is not found in 'contents'. Raises: KeyError: if 'key' is not in the Hybrid and 'default' and the 'default_factory' attribute are both None. Returns: Any: value matching key in 'contents' or 'default_factory' value. """ try: return self[key] except (KeyError, TypeError): if default is None: if self.default_factory is None: raise KeyError(f'{key} is not in the Hybrid') else: try: return self.default_factory() except TypeError: return self.default_factory else: return default
(self)
10,710
bunches.sequences
__setitem__
sets 'key' in 'contents' to 'value'. Args: key (Union[Any, int]): if key isn't an int, it is ignored (since the 'name' attribute of the value will be acting as the key). In such a case, the 'value' is added to the end of 'contents'. If key is an int, 'value' is assigned at the that index number in 'contents'. value (Any): value to be paired with 'key' in 'contents'.
def __setitem__(self, key: Union[Any, int], value: Any) -> None: """sets 'key' in 'contents' to 'value'. Args: key (Union[Any, int]): if key isn't an int, it is ignored (since the 'name' attribute of the value will be acting as the key). In such a case, the 'value' is added to the end of 'contents'. If key is an int, 'value' is assigned at the that index number in 'contents'. value (Any): value to be paired with 'key' in 'contents'. """ if isinstance(key, int): self.contents[key] = value else: self.add(value) return
(self, key: Union[Any, int], value: Any) -> NoneType
10,711
bunches.sequences
add
Tries to extend 'contents' with 'item'. Otherwise, it appends. The method will extend all passed sequences, except str types, which it will append. Args: item (Union[Any, Sequence[Any]]): item(s) to add to the 'contents' attribute.
def add(self, item: Union[Any, Sequence[Any]]) -> None: """Tries to extend 'contents' with 'item'. Otherwise, it appends. The method will extend all passed sequences, except str types, which it will append. Args: item (Union[Any, Sequence[Any]]): item(s) to add to the 'contents' attribute. """ if isinstance(item, Sequence) and not isinstance(item, str): self.contents.extend(item) else: self.contents.append(item) return
(self, item: Union[Any, collections.abc.Sequence[Any]]) -> NoneType
10,712
collections.abc
append
S.append(value) -- append value to the end of the sequence
null
(self, value)
10,713
collections.abc
clear
S.clear() -> None -- remove all items from S
null
(self)
10,715
collections.abc
extend
S.extend(iterable) -- extend sequence by appending elements from the iterable
null
(self, values)
10,716
bunches.sequences
get
Returns value in 'contents' or default options. Args: key (Hashable): key for value in 'contents'. default (Optional[Any]): default value to return if 'key' is not found in 'contents'. Raises: KeyError: if 'key' is not in the Hybrid and 'default' and the 'default_factory' attribute are both None. Returns: Any: value matching key in 'contents' or 'default_factory' value.
def get(self, key: Hashable, default: Optional[Any] = None) -> Any: # type: ignore """Returns value in 'contents' or default options. Args: key (Hashable): key for value in 'contents'. default (Optional[Any]): default value to return if 'key' is not found in 'contents'. Raises: KeyError: if 'key' is not in the Hybrid and 'default' and the 'default_factory' attribute are both None. Returns: Any: value matching key in 'contents' or 'default_factory' value. """ try: return self[key] except (KeyError, TypeError): if default is None: if self.default_factory is None: raise KeyError(f'{key} is not in the Hybrid') else: try: return self.default_factory() except TypeError: return self.default_factory else: return default
(self, key: collections.abc.Hashable, default: Optional[Any] = None) -> Any
10,718
bunches.sequences
insert
Inserts 'item' at 'index' in 'contents'. Args: index (int): index to insert 'item' at. item (Any): object to be inserted.
def insert(self, index: int, item: Any) -> None: """Inserts 'item' at 'index' in 'contents'. Args: index (int): index to insert 'item' at. item (Any): object to be inserted. """ self.contents.insert(index, item) return
(self, index: int, item: Any) -> NoneType
10,719
bunches.sequences
items
Emulates python dict 'items' method. Returns: tuple[tuple[Hashable, ...], tuple[Any, ...]]: a tuple equivalent to dict.items(). A Hybrid cannot actually create an ItemsView because that would eliminate any duplicate keys, which are permitted by Hybrid.
def items(self) -> tuple[tuple[Hashable, ...], tuple[Any, ...]]: """Emulates python dict 'items' method. Returns: tuple[tuple[Hashable, ...], tuple[Any, ...]]: a tuple equivalent to dict.items(). A Hybrid cannot actually create an ItemsView because that would eliminate any duplicate keys, which are permitted by Hybrid. """ return tuple(zip(self.keys(), self.values()))
(self) -> tuple[tuple[collections.abc.Hashable, ...], tuple[typing.Any, ...]]
10,720
bunches.sequences
keys
Emulates python dict 'keys' method. Returns: tuple[Hashable, ...]: a tuple equivalent to dict.keys(). A Hybrid cannot actually create an KeysView because that would eliminate any duplicate keys, which are permitted by Hybrid.
def keys(self) -> tuple[Hashable, ...]: """Emulates python dict 'keys' method. Returns: tuple[Hashable, ...]: a tuple equivalent to dict.keys(). A Hybrid cannot actually create an KeysView because that would eliminate any duplicate keys, which are permitted by Hybrid. """ return tuple([utilities.get_name(item = c) for c in self.contents])
(self) -> tuple[collections.abc.Hashable, ...]
10,721
collections.abc
pop
S.pop([index]) -> item -- remove and return item at index (default last). Raise IndexError if list is empty or index is out of range.
null
(self, index=-1)
10,722
bunches.sequences
prepend
Prepends 'item' to 'contents'. If 'item' is a non-str sequence, 'prepend' adds its contents to the stored list in the order they appear in 'item'. Args: item (Union[Any, Sequence[Any]]): item(s) to prepend to the 'contents' attribute.
def prepend(self, item: Union[Any, Sequence[Any]]) -> None: """Prepends 'item' to 'contents'. If 'item' is a non-str sequence, 'prepend' adds its contents to the stored list in the order they appear in 'item'. Args: item (Union[Any, Sequence[Any]]): item(s) to prepend to the 'contents' attribute. """ if isinstance(item, Sequence) and not isinstance(item, str): for thing in reversed(item): self.prepend(item = thing) else: self.insert(0, item) return
(self, item: Union[Any, collections.abc.Sequence[Any]]) -> NoneType
10,723
collections.abc
remove
S.remove(value) -- remove first occurrence of value. Raise ValueError if the value is not present.
null
(self, value)
10,724
collections.abc
reverse
S.reverse() -- reverse *IN PLACE*
null
(self)
10,725
bunches.sequences
setdefault
sets default value to return when 'get' method is used. Args: value (Any): default value to return.
def setdefault(self, value: Any) -> None: # type: ignore """sets default value to return when 'get' method is used. Args: value (Any): default value to return. """ self.default_factory = value return
(self, value: Any) -> NoneType
10,726
bunches.sequences
subset
Returns a new instance with a subset of 'contents'. This method applies 'include' before 'exclude' if both are passed. If 'include' is None, all existing keys will be added before 'exclude' is applied. Args: include (Optional[Union[Sequence[Any], Any]]): item(s) to include in the new instance. Defaults to None. exclude (Optional[Union[Sequence[Any], Any]]): item(s) to exclude in the new instance. Defaults to None. Raises: ValueError: if 'include' and 'exclude' are both None. Returns: Listing: with only items from 'include' and no items in 'exclude'.
def subset( self, include: Optional[Union[Sequence[Any], Any]] = None, exclude: Optional[Union[Sequence[Any], Any]] = None) -> Listing: """Returns a new instance with a subset of 'contents'. This method applies 'include' before 'exclude' if both are passed. If 'include' is None, all existing keys will be added before 'exclude' is applied. Args: include (Optional[Union[Sequence[Any], Any]]): item(s) to include in the new instance. Defaults to None. exclude (Optional[Union[Sequence[Any], Any]]): item(s) to exclude in the new instance. Defaults to None. Raises: ValueError: if 'include' and 'exclude' are both None. Returns: Listing: with only items from 'include' and no items in 'exclude'. """ if include is None and exclude is None: raise ValueError('include or exclude must not be None') else: if include is None: contents = self.contents else: include = list(utilities.iterify(item = include)) contents = [i for i in self.contents if i in include] if exclude is not None: exclude = list(utilities.iterify(item = exclude)) contents = [i for i in contents if i not in exclude] new_listing = copy.deepcopy(self) new_listing.contents = contents return new_listing
(self, include: Union[collections.abc.Sequence[Any], Any, NoneType] = None, exclude: Union[collections.abc.Sequence[Any], Any, NoneType] = None) -> bunches.sequences.Listing
10,727
bunches.sequences
update
Mimics the dict 'update' method by extending 'contents' with 'items'. Args: items (Mapping[Any, Any]): items to add to the 'contents' attribute. The values of 'items' are added to 'contents' and the keys become the 'name' attributes of those values. As a result, the keys of 'items' are discarded. To mimic dict' update', the passed 'items' values are added to 'contents' by the 'extend' method which adds the values to the end of 'contents'.
def update(self, items: Mapping[Any, Any]) -> None: """Mimics the dict 'update' method by extending 'contents' with 'items'. Args: items (Mapping[Any, Any]): items to add to the 'contents' attribute. The values of 'items' are added to 'contents' and the keys become the 'name' attributes of those values. As a result, the keys of 'items' are discarded. To mimic dict' update', the passed 'items' values are added to 'contents' by the 'extend' method which adds the values to the end of 'contents'. """ self.extend(list(items.values())) return
(self, items: collections.abc.Mapping[typing.Any, typing.Any]) -> NoneType
10,728
bunches.sequences
values
Emulates python dict 'values' method. Returns: tuple[Any, ...]: a tuple equivalent to dict.values(). A Hybrid cannot actually create an ValuesView because that would eliminate any duplicate keys, which are permitted by Hybrid.
def values(self) -> tuple[Any, ...]: """Emulates python dict 'values' method. Returns: tuple[Any, ...]: a tuple equivalent to dict.values(). A Hybrid cannot actually create an ValuesView because that would eliminate any duplicate keys, which are permitted by Hybrid. """ return tuple(self.contents)
(self) -> tuple[typing.Any, ...]
10,729
collections.abc
Iterable
null
from collections.abc import Iterable
()
10,731
collections.abc
Iterator
null
from collections.abc import Iterator
()
10,733
collections.abc
__next__
Return the next item from the iterator. When exhausted, raise StopIteration
null
(self)
10,734
bunches.mappings
Library
Stores classes and class instances. When searching for matches, instances are prioritized over classes. Args: classes (Catalog): a catalog of stored classes. Defaults to any empty Catalog. instances (Catalog): a catalog of stored class instances. Defaults to an empty Catalog. Attributes: maps (list[Catalog]): the ordered mappings to search, as required from inheriting from ChainMap.
class Library(MutableMapping): """Stores classes and class instances. When searching for matches, instances are prioritized over classes. Args: classes (Catalog): a catalog of stored classes. Defaults to any empty Catalog. instances (Catalog): a catalog of stored class instances. Defaults to an empty Catalog. Attributes: maps (list[Catalog]): the ordered mappings to search, as required from inheriting from ChainMap. """ classes: Catalog = dataclasses.field(default_factory = dict) instances: Catalog = dataclasses.field(default_factory = dict) """ Public Methods """ def deposit( self, item: Union[Type[Any], object], name: Optional[Hashable] = None) -> None: """Adds 'item' to 'classes' and/or 'instances'. If 'item' is a class, it is added to 'classes.' If it is an object, it is added to 'instances' and its class is added to 'classes'. Args: item (Union[Type, object]): class or instance to add to the Library instance. name (Optional[Hashable]): key to use to store 'item'. If not passed, a key will be created using the 'get_name' method. """ key = name or utilities.get_name(item = item) if inspect.isclass(item): self.classes[key] = item elif isinstance(item, object): self.instances[key] = item self.deposit(item = item.__class__) else: raise TypeError(f'item must be a class or a class instance') return def remove(self, item: Hashable) -> None: """Removes an item from 'instances' or 'classes.' If 'item' is found in 'instances', it will not also be removed from 'classes'. Args: item (Hashable): key name of item to remove. Raises: KeyError: if 'item' is neither found in 'instances' or 'classes'. """ try: del self.instances[item] except KeyError: try: del self.classes[item] except KeyError: raise KeyError(f'{item} is not found in the Library') return def withdraw( self, item: Union[Hashable, Sequence[Hashable]], kwargs: Optional[MutableMapping[Hashable, Any]] = None) -> ( Union[Type[Any], object]): """Returns instance or class of first match of 'item' from catalogs. The method prioritizes the 'instances' catalog over 'classes' and any passed names in the order they are listed. Args: item (Union[Hashable, Sequence[Hashable]]): key name(s) of stored item(s) sought. kwargs (Optional[MutableMapping[Hashable, Any]]]): keyword arguments to pass to a newly created instance or, if the stored item is already an instance to be manually added as attributes. If not passed, the found item will be returned unaltered. Defaults to None. Raises: KeyError: if 'item' does not match a key to a stored item in either 'instances' or 'classes'. Returns: Union[Type[Any], object]: returns a class or instance if 'kwargs' are None, depending upon with Catalog the matching item is found. If 'kwargs' are passed, an instance is always returned. """ items = utilities.iterify(item) item = None for key in items: for catalog in ['instances', 'classes']: try: item = getattr(self, catalog)[key] break except KeyError: pass if item is not None: break if item is None: raise KeyError(f'No matching item for {item} was found') if kwargs is not None: if 'item' in item.__annotations__.keys() and 'item' not in kwargs: kwargs[item] = items[0] if inspect.isclass(item): item = item(**kwargs) else: for key, value in kwargs.items(): setattr(item, key, value) return item # type: ignore """ Dunder Methods """ def __getitem__(self, key: Hashable) -> Any: """Returns value for 'key' in 'contents'. Args: key (Hashable): key in 'contents' for which a value is sought. Returns: Any: value stored in 'contents'. """ return self.withdraw(item = key) def __setitem__(self, key: Hashable, value: Any) -> None: """sets 'key' in 'contents' to 'value'. Args: key (Hashable): key to set in 'contents'. value (Any): value to be paired with 'key' in 'contents'. """ self.deposit(item = value, name = key) return def __delitem__(self, key: Hashable) -> None: """Deletes 'key' in 'contents'. Args: key (Hashable): key in 'contents' to delete the key/value pair. """ self.remove(item = key) return def __iter__(self) -> Iterator[Any]: """Returns iterable of 'contents'. Returns: Iterator: of 'contents'. """ combined = copy.deepcopy(self.instances) return iter(combined.update(self.classes)) def __len__(self) -> int: """Returns length of 'contents'. Returns: int: length of 'contents'. """ combined = copy.deepcopy(self.instances) return len(combined.update(self.classes))
(classes: bunches.mappings.Catalog = <factory>, instances: bunches.mappings.Catalog = <factory>) -> None
10,736
bunches.mappings
__delitem__
Deletes 'key' in 'contents'. Args: key (Hashable): key in 'contents' to delete the key/value pair.
def __delitem__(self, key: Hashable) -> None: """Deletes 'key' in 'contents'. Args: key (Hashable): key in 'contents' to delete the key/value pair. """ self.remove(item = key) return
(self, key: collections.abc.Hashable) -> NoneType
10,738
bunches.mappings
__getitem__
Returns value for 'key' in 'contents'. Args: key (Hashable): key in 'contents' for which a value is sought. Returns: Any: value stored in 'contents'.
def __getitem__(self, key: Hashable) -> Any: """Returns value for 'key' in 'contents'. Args: key (Hashable): key in 'contents' for which a value is sought. Returns: Any: value stored in 'contents'. """ return self.withdraw(item = key)
(self, key: collections.abc.Hashable) -> Any
10,740
bunches.mappings
__iter__
Returns iterable of 'contents'. Returns: Iterator: of 'contents'.
def __iter__(self) -> Iterator[Any]: """Returns iterable of 'contents'. Returns: Iterator: of 'contents'. """ combined = copy.deepcopy(self.instances) return iter(combined.update(self.classes))
(self) -> collections.abc.Iterator[typing.Any]
10,741
bunches.mappings
__len__
Returns length of 'contents'. Returns: int: length of 'contents'.
def __len__(self) -> int: """Returns length of 'contents'. Returns: int: length of 'contents'. """ combined = copy.deepcopy(self.instances) return len(combined.update(self.classes))
(self) -> int
10,743
bunches.mappings
__setitem__
sets 'key' in 'contents' to 'value'. Args: key (Hashable): key to set in 'contents'. value (Any): value to be paired with 'key' in 'contents'.
def __setitem__(self, key: Hashable, value: Any) -> None: """sets 'key' in 'contents' to 'value'. Args: key (Hashable): key to set in 'contents'. value (Any): value to be paired with 'key' in 'contents'. """ self.deposit(item = value, name = key) return
(self, key: collections.abc.Hashable, value: Any) -> NoneType