Browse Source

Extract convert_item function

doc-issue-template
MrS0m30n3 7 years ago
parent
commit
882a710b24
1 changed files with 31 additions and 30 deletions
  1. 61
      youtube_dl_gui/utils.py

61
youtube_dl_gui/utils.py

@ -53,48 +53,49 @@ def get_encoding():
return encoding
def convert_on_bounds(func):
"""Decorator to convert string inputs & outputs.
def convert_item(item, to_unicode=False):
"""Convert item between 'unicode' and 'str'.
Covert string inputs & outputs between 'str' and 'unicode' at the
application bounds using the preferred system encoding. It will convert
all the string params (args, kwargs) to 'str' type and all the
returned strings values back to 'unicode'.
Args:
item (-): Can be any python item.
to_unicode (boolean): When True it will convert all the 'str' types
to 'unicode'. When False it will convert all the 'unicode'
types back to 'str'.
"""
def convert_item(item, to_unicode=False):
"""The actual function which handles the conversion.
if to_unicode and isinstance(item, str):
# Convert str to unicode
return item.decode(get_encoding(), 'ignore')
Args:
item (-): Can be any python item.
if not to_unicode and isinstance(item, unicode):
# Convert unicode to str
return item.encode(get_encoding(), 'ignore')
to_unicode (boolean): When True it will convert all the 'str' types
to 'unicode'. When False it will convert all the 'unicode'
types back to 'str'.
if hasattr(item, '__iter__'):
# Handle iterables
temp_list = []
"""
if to_unicode and isinstance(item, str):
# Convert str to unicode
return item.decode(get_encoding(), 'ignore')
for sub_item in item:
if isinstance(item, dict):
temp_list.append((sub_item, convert_item(item[sub_item])))
else:
temp_list.append(convert_item(sub_item))
if not to_unicode and isinstance(item, unicode):
# Convert unicode to str
return item.encode(get_encoding(), 'ignore')
return type(item)(temp_list)
if hasattr(item, '__iter__'):
# Handle iterables
temp_list = []
return item
for sub_item in item:
if isinstance(item, dict):
temp_list.append((sub_item, convert_item(item[sub_item])))
else:
temp_list.append(convert_item(sub_item))
return type(item)(temp_list)
def convert_on_bounds(func):
"""Decorator to convert string inputs & outputs.
return item
Covert string inputs & outputs between 'str' and 'unicode' at the
application bounds using the preferred system encoding. It will convert
all the string params (args, kwargs) to 'str' type and all the
returned strings values back to 'unicode'.
"""
def wrapper(*args, **kwargs):
returned_value = func(*convert_item(args), **convert_item(kwargs))

Loading…
Cancel
Save