[docs]classItemFromList:# pylint: disable=too-few-public-methods"""Coerce single-item lists into just the only item in the list. Returns item if item is not a list, set, or tuple. Raises CoerceInvalid if impossible. Examples -------- >>> ItemFromList(['seagull']) 'seagull' >>> ItemFromList(['two', 'seagulls']) Traceback (most recent call last): ... voluptuous.error.CoerceInvalid: Cannot coerce list of length 2 to item >>> ItemFromList('string') 'string' """def__new__(cls,list_of_one,msg=None):"""Initialize item from list"""fromvoluptuousimportCoerceInvalid,Length,LengthInvalidifnotisinstance(list_of_one,(list,set,tuple)):returnlist_of_onetry:Length(max=1)(list_of_one)exceptLengthInvalidaslength_invalid:raiseCoerceInvalid(f'Cannot coerce list of length {len(list_of_one)} to item'ifmsgisNoneelsemsg)fromlength_invalidreturnlist_of_one[0]
[docs]classListFromItem(list):"""Subclass of list to coerce non-lists into lists Examples -------- >>> list('one') ['o', 'n', 'e'] >>> ListFromItem('one') ['one'] >>> list(['one']) ['one'] >>> ListFromItem(['one']) ['one'] >>> list() [] >>> ListFromItem() [] >>> list(None) Traceback (most recent call last): ... TypeError: 'NoneType' object is not iterable >>> ListFromItem(None) [] """def__init__(self,*args,**kwargs):"""Initialize ListFromItem"""iflen(args)==1andnotisinstance(args[0],(list,tuple)):ifargs[0]isNone:args=()else:args=([args[0]],)list.__init__(self,*args,**kwargs)