auto_list¶
-
privex.helpers.common.auto_list(obj: V, conv: Union[Type[T], Callable[[V], T]] = <class 'list'>, force_wrap=False, force_iter=False, **kw) → T[source]¶ Used for painless conversion of various data types into list-like objects (
list/tuple/setetc.)Ensure object
objis a list-like object of typeconv, if it isn’t, then attempt to convert it into an instance ofconvvia either list wrapping, or list iterating, depending on the type thatobjis detected to be.Examples:
>>> auto_list('hello world') ['hello world'] >>> auto_list('lorem ipsum', conv=set) {'lorem ipsum'} >>> auto_list('hello world', force_iter=True) ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] >>> auto_list(('this', 'is', 'a', 'test',)) ['this', 'is', 'a', 'test'] >>> auto_list(('this', 'is', 'a', 'test',), force_wrap=True) [('this', 'is', 'a', 'test')]
List Wrapping
The list wrapping conversion method is when we wrap an object with list brackets, i.e.
[obj]. which makes theobja single item inside of a new list.This is important for simple single-value data types such as
str,bytes, integers, floats etc. - since usinglist()might simply iterate over their contents, e.g. turnining"hello"into['h', 'e', 'l', 'l', 'o'], which is rarely what you intend when you want to convert an object into a list.This method is used by default for the types:
str, bytes, int, float, Decimal, bool, dict
To force conversion via List Wrapping, set the argument
force_wrap=TrueList Iteration / Iterating
The list iteration method is when we call
list(obj)to convertobj‘s contents into a list, rather than makingobjan item inside of the list.This is important for other list-like data types such as
list/set/tupleetc., since with the List Wrapping method, it would result in for example, a set{'hello', 'world'}simply being wrapped by a list[{'hello', 'world'}], instead of converting it into a list.To force conversion via List Iteration, set the argument
force_iter=TrueThis method is used bt default for the types:
list, set, tuple, range any object which didn't match the list wrapping type checks and has the method: __iter__
- Parameters
obj (V|any) – An object of practically any type, to convert into an instance type of
convconv (T|type|callable) – A
typewhich is also callable withobjas the first positional argument, to convertobjinto aconvinstance.force_wrap (bool) – When set to
True,objwill always be converted intoconvusing the list wrapping methodconv([obj]), regardless of whether it’s a type that should or shouldn’t be wrapped.force_iter (bool) – When set to
True,objwill always be converted intoconvusing the list iterator method, i.e.conv(list(obj)), regardless of whether it’s a type that should or shouldn’t be iterated.zero (bool) – Passthru argument to
empty()(treat the number0as empty)itr (bool) – Passthru argument to
empty()(treat zero-length iterables as empty)
- Return T|list|set|tuple data
The object
objafter converting it into aconvinstance