1

Pretty odd question but is it possible to overload the meaning of certain bracket types e.g. <, >, [, ] and | in Python. For instance if I have some object instances MyObj1 and MyObj2 could I design something whereby <MyObj1 | MyObj2 > was understood as either a method call in MyObj1?

I think it probably can't/shouldn't be done but I thought I'd ask!

3
  • Uhhhhh... Why? EDIT: Also, no it's not possible unless you fork CPython and write the code yourself to support it. Commented Jan 23, 2015 at 13:24
  • 1
    Although you can overload operators, you cannot change their arity. Both < and > are binary operators that require two operands, even if you overload them. Commented Jan 23, 2015 at 13:26
  • Yeah I thought it might have been a bit far out but by way of a quick explaination I wanted to write something to compute Bra-Kets (en.wikipedia.org/wiki/Bra%E2%80%93ket_notation) conveniently and in a syntactically similar fashion Commented Jan 23, 2015 at 13:32

1 Answer 1

4

No. The only operator overloading that is allowed in Python is changing the runtime semantics of pre-existing operators. The syntax <MyObj1 | MyObj2 > would involve either making < and > into unary operators (one prefix, one postfix) or making them both into a single "circumfix" operator. As they are currently both binary infix operators, such a change cannot be done.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.