Skip to content

Instantly share code, notes, and snippets.

@datashaman
Last active March 10, 2023 08:23
Show Gist options
  • Save datashaman/cdc28e67332647ed4ec53b91e93f9226 to your computer and use it in GitHub Desktop.
Save datashaman/cdc28e67332647ed4ec53b91e93f9226 to your computer and use it in GitHub Desktop.
Get names
strategies = [
{
'type': str,
'return': lambda input: [input.strip()] if input.strip() else [],
},
{
'type': dict,
'return': lambda input: [input.get('name')] if input.get('name') else [],
},
{
'type': (list, tuple),
'return': lambda input: [name for item in input for name in get_names(item)],
},
{
'type': None.__class__,
'return': lambda input: []
},
]
def get_names(input=None) -> list:
return [
name
for strategy in strategies if isinstance(input, strategy['type'])
for name in strategy['return'](input)
]
print(get_names())
print(get_names(''))
print(get_names({
'name': 'something',
'code': 1,
}))
print(get_names([
{
'name': 'something',
'code': 1,
},
{
'name' : 'something else',
'code': 2,
},
]))
print(get_names([
None,
'',
{
'name': 'one',
'code': 1,
},
[
{
'name': 'two',
'code': 1,
},
{
'name' : 'three',
'code': 2,
},
],
[
'four',
'five',
'six',
'',
{
'name': 'seven',
'code': 1,
},
{
'name' : 'eight',
'code': 2,
},
[
'nine',
None,
'ten',
'',
{
'name': '',
'code': 1,
},
{
'name' : 'eleven',
'code': 2,
},
],
],
]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment