I am analyzing the source code for BeautifulSoup, and within the @string.setter property, I noticed a cryptic string assignment, and I am wondering if there is something gained by this that I am unaware of?
From BeautilfulSoup's element.py Tag-class:
@property
def string(self):
"""Convenience property to get the single string within this tag.
:Return: If this tag has a single string child, return value
is that string. If this tag has no children, or more than one
child, return value is None. If this tag has one child tag,
return value is the 'string' attribute of the child tag,
recursively.
"""
if len(self.contents) != 1: return None
child = self.contents[0]
if isinstance(child, NavigableString): return child
return child.string
@string.setter
def string(self, string):
self.clear()
self.append(string.__class__(string))
My question is with the last line. There is not check on type(...)
so couldn't they just use: self.append(string)
?
I have ran my own bit of code to see what this last line is doing, and it just seems the value of the variable is being set...
>>> x = "my-string"
>>> x.__class__
<class 'str'>
>>> x.__class__(x)
'my-string'
>>> type(x.__class__(x))
<class 'str'>
>>>
So I wonder what the reasoning for this is? Is there something gained our is this just a preference from the developer?