flakes
flakes

Reputation: 23674

Is str("str") always an identity function?

So simple question here:

I see for certain objects that a call to str can actually create a new object reference

>>> a = 1
>>> str(a) is str(a)
False

However, I notice that this is not true for strings (which seems intuitive). Does the str method always act as an identity function for str objects? Or does this property just seem correct due to string interning optimizations, and may not actually return the same reference?

>>> a = "1"
>>> a is str(a)
True
>>> str(a) is str(a)
True

Is this a global rule/ language specification rule, or is it going to be interpreter dependent?

FWIW I'm asking this question because in a few places I safeguard some methods to ensure a str instance is used. I wanted to know if I'm creating garbage by adding the redundant str call around inputs which are already type str. e.g.

def safeguard_foo(val):
    foo(str(val))

Another option is to safeguard in a more verbose fashion (it's worth noting that this method is about 25% faster anyways, so in terms of performance it wins out even before considering the garbage creation concerns). e.g.

def safeguard_foo(val):
    if not isinstance(val, str):
        val = str(val)
    foo(val)

Upvotes: 5

Views: 294

Answers (0)

Related Questions