Merge pull request #133 from lanzhiwang/master

fix cast_list
This commit is contained in:
Angelos Chalaris
2019-10-09 13:14:46 +03:00
committed by GitHub

View File

@ -5,14 +5,15 @@ tags: utility,list,beginner
Casts the provided value as an array if it's not one.
Use `isinstance()` to check if the given value is a list and return it as-is or encapsulated in a list accordingly.
Use `isinstance()` to check if the given value is enumerable and return it by using `list()` or encapsulated in a list accordingly.
```py
def cast_list(val):
return val if isinstance(val, list) else [val]
return list(val) if isinstance(val, (tuple, list, set, dict)) else [val]
```
```py
cast_list('foo'); # ['foo']
cast_list([1]); # [1]
cast_list('foo') # ['foo']
cast_list([1]) # [1]
cast_list(('foo', 'bar')) # ['foo', 'bar']
```