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
/set
etc.)Ensure object
obj
is a list-like object of typeconv
, if it isn’t, then attempt to convert it into an instance ofconv
via either list wrapping, or list iterating, depending on the type thatobj
is 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 theobj
a 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=True
List Iteration / Iterating
The list iteration method is when we call
list(obj)
to convertobj
‘s contents into a list, rather than makingobj
an item inside of the list.This is important for other list-like data types such as
list
/set
/tuple
etc., 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=True
This 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
conv
conv (T|type|callable) – A
type
which is also callable withobj
as the first positional argument, to convertobj
into aconv
instance.force_wrap (bool) – When set to
True
,obj
will always be converted intoconv
using 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
,obj
will always be converted intoconv
using 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 number0
as empty)itr (bool) – Passthru argument to
empty()
(treat zero-length iterables as empty)
- Return T|list|set|tuple data
The object
obj
after converting it into aconv
instance