Niklas Rosencrantz
Niklas Rosencrantz

Reputation: 26642

Why use str(id)?

My SDK comes with code appearing with rows like this

id=str(profile["id"])

It makes me wonder why something like the following shouldn't work

id=profile["id"]

Casting I believe is expensive so either the same type can be used or polymorphism at the method called. Can you tell why I must cast the id to a string? Thank you

Upvotes: 0

Views: 984

Answers (4)

Saynur Altin
Saynur Altin

Reputation: 1

It turns profile[id] into a string

Upvotes: 0

Insomaniacal
Insomaniacal

Reputation: 1997

It turns profile[id] into a string, python doesn't do this automatically, and further along in the code, the program probably checks profile[id] against a string. Without this conversion, you would get a typeerror: Trying to compare a string with an integer.

Upvotes: 3

Lennart Regebro
Lennart Regebro

Reputation: 172319

There is no casting in Python. Str(67) does not cast. It calls the __str__ method on the integer object, which generates a string representation of itself.

This is necessary to make sure that profile['id'] is a string.

Upvotes: 3

Tyler Eaves
Tyler Eaves

Reputation: 13133

Python does not do arbitrary run time type conversion. You can't use an integer as a string.

Upvotes: 1

Related Questions