creating a new object based on the type of the given object in python

Viewed 66

I have a function that gets a sequence as a parameter and based on the type of that sequence, it creates a new object of that type.

def myFunc(seq):
    new_object = # don't know how to instantiate it based on seq type.

For example, if 'seq' is a list, 'new_object' will be an empty list. Or if 'seq' is a string, 'new_object' will be an empty string and so on.

How can I do that??

3 Answers

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 

You could access its __class__() attribute.

def empty(obj):
    return obj.__class__()

print(empty(2))  # -> 0
print(empty([1,2,3]))  # -> []

since your object is a sequence you can use a slice to get a new object of the same type but empty:

def make_empty(obj):
    return obj[:0]

make_empty(['a', 'b', 'c'])

output:

[]
Related