I want this code to "just work":
def main():
c = Castable()
print c/3
print 2-c
print c%7
print c**2
print "%s" % c
print "%i" % c
print "%f" % c
Of course, the easy way out is to write int(c)/3
, but I'd like to enable a simpler perl-ish syntax for a configuration mini-language.
It's notable that if I use an "old-style" class (don't inherit from object) I can do this quite simply by defining a __coerce__
method, but old-style classes are deprecated and will be removed in python3.
When I do the same thing with a new-style class, I get this error:
TypeError: unsupported operand type(s) for /: 'Castable' and 'int'
I believe this is by design, but then how can I simulate the old-style __coerce__
behavior with a new-style class? You can find my current solution below, but it's quite ugly and long-winded.
This is the relevant documentation: (i think)
Bonus points:
print pow(c, 2, 100)