What benefit do you see in having this second way to spell what it
"123" as int
Why is the second better?
It’s also a bit weird, because sometimes “as” will bind a name:
import module as spam # binds the module to name "spam"
except TypeError as err: # binds the exception to name "err"
with open(filename) as f: # binds the open file object to name "f"
and sometimes it won’t:
"123" as int # binds the value to "int"? No it doesn't!!!
So this is going to be awfully confusing to people trying to learn what
“as” does. Imagine something like this for extra confusion:
with obj as SpecialThing as cm:
# with SpecialThing(obj) as cm
How does this special method
__as__ work? Your example isn’t clear:
def __init__(self, number):
self.number = number as int
def __as__(self, o):
return (o as int)*self.number
MyObject("5") as 10 # 50
So we have:
MyObject("5") as 3.5 # returns 15
MyObject("5") as "4" # returns 20
MyObject("5") as int # raises
# TypeError: int() argument must be a string, a bytes-like object or a number, not 'type'