Duck Typing in general is explained here: https://stackoverflow.com/a/4205163/19446851.
What does Duck Typing mean in Python? Is it really possible to make one type look like another type. Can I have an own class that "looks and quacks" like a string?
See the following example:
from dataclasses import dataclass
@dataclass
class ColoredObject:
color : ...
name : ...
def __str__(self):
return self.color + " " + self.name
x = ColoredObject("red", "circle")
print("I have a " + x + ".")
That code does not work because strings and objects of the type ColoredObject cannot be concatenated. If in Python it would actually be possible to make ColoredObject "look and quack" like a string, there should be a way to concatenate both without the explicit conversion.
The following is a more practical example. I try to make the class MutableText "looking and quacking" like a string so that I can use it in an XML Element Tree.
import xml.etree.cElementTree as ET
root = ET.Element("root_node")
class MutableText:
def __init__(self, init_text):
self.text = init_text
mutable_contents = MutableText("ZigZag")
ET.SubElement(root, "child_node").text = mutable_contents
tree = ET.ElementTree(root)
tree.write("filename.xml")
The goal is that line ET.SubElement(root, "child_node").text = mutable_contents
works. What can I do to achieve this?
The error message, that I get with the code is TypeError: cannot serialize <__main__.MutableText object at 0x7fafc0099e20> (type MutableText)
I already got the advice to inherit from str class. But this is not Duck Typing. This is static typing like in C++ or Java.
Another advice to use ET.SubElement(root, "child_node").text = mutable_contents.text
is good. But that is also not Duck Typing. And that means, I always have to update the ElementTree whenever mutable_contents changes. (This is actually my motivation, why I ask this academic question. I am trying to find a solution for not having to always do this update.)
I also got the comment that ElementTree actually expects a string and not a MutableString. But why do people then say, Python uses Duck Typing? And why don't I get the error Message that a string is expected where a MutableString is provided?
Obviously there is something missing in my code in order to make MutableText like a string? But what is missing? And shouldn't Python give me an error message when it tries to call something from MutableText, which is missing?