2

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 3

2

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 
Sign up to request clarification or add additional context in comments.

2 Comments

the fact that your function works well also with no sequence can't be also a bad thing? I mean if the given object it is not a sequence the expected behaviour will be to raise an exception
@kederrac good point there. we can check the type of given object first, if it is a sequence then we call 'make_empty' function.
0

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:

[]

Comments

0

You could access its __class__() attribute.

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.