pyview
pyview

Reputation: 23

pythonic way to return object based on parameter type

I have a simple class that can operate on a variety of base classes (strings, list, file... handed to it in Python3.x and return the same type. For now, I am using isinstance for type checking though have read all the admonishments of doing so.

My question is what is the pythonic way of writing this function. 'Duck typing' seems more appropriate for testing that the correct type was used. I considered overloading with passing type [func(type, input)] or testing for hasattr. I want the code to be consistent with best practices, future friendly and up-gradable by a programmer other than myself.

Upvotes: 2

Views: 244

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 118031

Rather than checking the actual type of the object, you should check the behavior of the object.

What I mean by that is rather than

isinstance(foo, str) or isinstance(foo, list) or ...

You are more interested in whether it is a sequence, meaning it has defined __iter__ for example

hasattr(foo, '__iter__')

In this sense you don't really care what the object is per se, rather you just want the objects to behave a certain way.

Similarly if you wanted the objects to be "index-able" you could check

hasattr(foo, '__getitem__')

You could follow this pattern to enforce your "duck typing" design.

Upvotes: 2

Related Questions