0

Recently I was reading about magic methods in Python, which make the code a lot easier to read. Can we define our own mappings? If so, is there any pointer for this and how complicated it would be?

For example, + is always mapped to __add__. Could I define a mapping for ?, which would call __is_valid__ in my class?

c = Car()
print(c?)  # invokes __is_valid__ of Car to get the result
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • You are really try to change python syntax. Question mark has no special meaning. To do that, you have to change tokenizer in python, syntax analysis (for example define priority) and that is too much work only for syntax sugar. Why don't use standart way: print(c.is_valid())? Creating a new operator do not get rid you duty of implement this method. c.is_valid can read everyone imediately, c? is something new. – lofcek Aug 14 '16 at 08:55
  • Or just implement a `@property` and use `c.valid`. – jonrsharpe Aug 14 '16 at 09:09
  • @jonrsharpe: I don't think this is really a duplicate of that other question. That question is asking about adding statements, and the answers get into bytecode generation and stuff. This question is asking about creating new operators and mapping them to magic methods, which is a somewhat more limited form of syntax change. (I wouldn't be surprised if there is a real duplicate out there somewhere though.) – BrenBarn Aug 14 '16 at 09:19

1 Answers1

0

You seem to be asking if you can create your own syntax in Python, adding new symbols that are implemented via magic methods. The answer is no. The only operators available are the ones that already exist (+, *, etc.), and each has its corresponding magic methods. You can't add new ones.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • Hmm .. Reasonable. So it means I can t change the binding as well. Meaning + will always call `__add__` and not any other custom defined method `__some_impl__`. Is that right ? – worldofprasanna Aug 14 '16 at 08:36
  • @worldofprasanna: Right. (I mean, it might also call `__radd__` or the other ones it's defined to call under certain circumstances, but the rules for what magic method each operator calls are fixed and you can't change them.) – BrenBarn Aug 14 '16 at 08:46