"""Base utilities."""# -*- coding: utf-8 -*-## This file is subject to the terms and conditions defined in# file 'LICENSE.txt', which is part of this source code package.### %% Importsfromfunctoolsimportwrapsimportnumpyasnp# %% Functions
[docs]defgenerate_random_ASCII(size:int=16)->str:"""Generate a random ASCII string of the specified size. Args: size (int, optional): The length of the generated string. Defaults to 16. Returns: str: A random ASCII string of the specified size. """assertsize>=1rnd_=chr(np.random.randint(65,91))for_inrange(size-1):val_=np.random.randint(91-65+10)ifval_>=10:rnd_+=chr(val_-10+65)else:rnd_+=str(val_)returnrnd_
[docs]defsafe_len(obj):"""Safely return the length of an object, or 0 if the object has no length. Parameters ---------- obj : Any The object whose length is to be computed. Returns: ------- int The length of the object if it defines `__len__`, otherwise 0. """returnlen(obj)ifhasattr(obj,"__len__")else0
[docs]defdelegate_methods(to:str,methods:list[str]):"""Class decorator to forward specific methods from a delegate attribute."""defwrapper(cls):fornameinmethods:defmake_delegate(name):@wraps(getattr(getattr(cls,to,None),name,lambda*_,**__:None))defmethod(self,*args,**kwargs):returngetattr(getattr(self,to),name)(*args,**kwargs)returnmethodsetattr(cls,name,make_delegate(name))returnclsreturnwrapper
[docs]classNotAllowedError(Exception):"""Exception for not allowed usage."""pass
[docs]classShapeError(Exception):"""Exception for badly shaped tensors."""pass
[docs]classDeprecatedError(Exception):"""Exception for deprecated methods."""pass