This works:
def make_empty(obj):
return type(obj)()
>>> make_empty([1, 2, 3])
[]
>>> make_empty('abc')
''
Works also for numbers not only sequences:
>>> make_empty(2)
0
or dictionaries:
>>> make_empty({'a': 100})
{}
Use type to get the type of the object and use () to create new, empty instance of it.
A version that allows to specified the allowed types:
def make_empty(obj, allowed_types=None):
if allowed_types is None:
return type(obj)()
for typ in allowed_types:
if isinstance(obj, typ):
return type(obj)()
raise TypeError(f'Type {type(obj)} not allowed')
Now.
It still works non-sequences:
>>> make_empty(3)
0
But the allowed types can be specified:
>>> make_empty(3, allowed_types=(str, list, tuple))
...
TypeError: Type <class 'int'> not allowed
The sequences work if allowed:
>>> make_empty('abc', allowed_types=(str, list, tuple))
''
>>> make_empty([1, 2, 3], allowed_types=(str, list, tuple))
[]
>>> make_empty((1, 2, 3), allowed_types=(str, list, tuple))
()
A dictionary does not if not allowsd:
>>> make_empty({'a': 100}, allowed_types=(str, list, tuple))
...
TypeError: Type <class 'dict'> not allowed