Ability to convert types by "as" keyword

What about ability to convert types by “as” keyword, for example "123" as int is the same as int("123")
And method for this:

class MyObject:
    def __init__(self, number):
        self.number = number as int

    def __as__(self, o):
        return (o as int)*self.number


MyObject("5") as 10 # 50

What benefit do you see in having this second way to spell what it
already possible?

int("123")
"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:

class MyObject:
    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

but:

MyObject("5") as int  # raises
# TypeError: int() argument must be a string, a bytes-like object or a number, not 'type'
1 Like