Reputation: 26642
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
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
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
Reputation: 13133
Python does not do arbitrary run time type conversion. You can't use an integer as a string.
Upvotes: 1