Create syntactic sugar to define a variable as a class instance

610 views Asked by At

I'm trying to create my own class that acts like a regular type, like this:

class CustomType:
    def __init__(self, content):
        self.content = content
    def __str__(self):
        return self.content

This means I can do something like this:

a = CustomType("hi there")
print(a)  # 'hi there'

But the problem is that I have to use a = CustomType("hi there"). Is there a way I can do something like a = /hi there\ or a similar solution that lets me create my own syntactic sugar?

Thanks.

2

There are 2 answers

0
jwodder On

No. Python does not support creating new syntax.

0
Brett Beatty On

Note: I would not suggest doing this.

You can't do that because the parser wouldn't know to look for it, but if you wanted something similar, you could create a custom class that returns a new instance of CustomType when divided by a string:

class CustomSyntax:
    def __truediv__(self, value):
        return CustomType(value)

Then if you had an instance of that class (let's call it c), you could divide it by a string any time you wanted an instance of CustomType:

a = c/'hi there'
b = c/'hello world'

However, that's a little weird, and you'd be best off sticking to your regular constructor.