Roscoe Roscoe - 1 month ago 10
Python Question

Does this qualify as polymorphism?

I'm trying to get a grasp on the concept of polymorphism and I kind of understand what it is in the context of OOP, but I've read that it can also apply to procedural programming and I don't really understand how.

I know that there's a bunch of methods and operators in Python, for example, which already use polymorphism, but what function that I write would qualify as polymorphic? For example, would the function what_type below be considered polymorphic, because by definition it has different behaviour based on the data type of the parameter it takes in, or is this just a regular example of a function with conditional statements in it?

def what_type(input_var):
'Returns a statement of the data type of the input variable'

# If the input variable is a string
if type(input_var) is str:
this_type = "This variable is a string!"

# If it's an integer
elif type(input_var) is int:
this_type = "This variable is an integer!"

# If it's a float
elif type(input_var) is float:
this_type = "This variable is a float!"

# If it's any other type
else:
this_type = "I don't know this type!"


return this_type

Answer

Perhaps it could be considered a rather uninteresting example of ad-hoc polymoriphism, but it isn't the sort of thing most people have in mind when they talk about polymorphism.

In addition to the OOP-style polymoriphism which you seem to be somewhat comfortable with, Python has an interesting protocol-based polymorphism. For example, iterators are objects which implement a __next__() method. You can write polymorphic functions which work with any iterator. For example, if you wanted to wrap two iterators into one which alternates between the two you could do something like this:

def alternate(source1,source2):
    for x,y in zip(source1,source2):
        yield x
        yield y

This could be applied to strings:

>>> for item in alternate("cat","dog"): print(item)

c
d
a
o
t
g

but it could be equally applied to e.g. two files that are open for reading.

The point of such polymorphic code is you really don't care what type of iterators are passed to it. As long as they are iterators, the code will work as expected.