Asked By – keys
How does python handle generic/template type scenarios? Say I want to create an external file “BinaryTree.py” and have it handle binary trees, but for any data type.
So I could pass it the type of a custom object and have a binary tree of that object. How is this done in python?
Now we will see solution for issue: Generics/templates in python?
Python uses duck typing, so it doesn’t need special syntax to handle multiple types.
If you’re from a C++ background, you’ll remember that, as long as the operations used in the template function/class are defined on some type
T (at the syntax level), you can use that type
T in the template.
So, basically, it works the same way:
- define a contract for the type of items you want to insert in the binary tree.
- document this contract (i.e. in the class documentation)
- implement the binary tree using only operations specified in the contract
You’ll note however, that unless you write explicit type checking (which is usually discouraged), you won’t be able to enforce that a binary tree contains only elements of the chosen type.