Aguy
Aguy

Reputation: 8059

Can I create a class that will be created by non trivial syntax?

Consider for example Quaternion math (https://en.wikipedia.org/wiki/Quaternion).

Obviously I can build a class that will define a new quaternion by

a = quaternion(1, 2, 3, 4)
print(a)
# 1 + 2i + 3j + 4k

However, one cannot help noticing that the native complex data type can be defined in a much nicer way by using

a = 1 + 2j
type(a)
# complex or <class 'complex'> depending if ipython or python

The 1 + 2j syntax is somehow captured to create the builtin class object complex(1,2).

So, can I do the same? Is there a way to capture a simple direct syntax such as a = 1 + 2i + 3j + 4k and translate it to my a = quartenion(1, 2, 3, 4) in a way similar to the workings of the builtin complex?

Upvotes: 4

Views: 95

Answers (2)

Tamas Hegedus
Tamas Hegedus

Reputation: 29916

You could define unit quaternions, define addition and subtraction to work with simple numbers too, and then just write expressions.

# quaternion.py
...
i = quaternion(0, 1, 0, 0)
j = quaternion(0, 0, 1, 0)
k = quaternion(0, 0, 0, 1)

# main.py
from quaternion import i,j,k
a = 1 + 2*i + 3*j + 4*k

It is not exactly the syntax you wanted, but it is close to it and has the same meaning.

Upvotes: 4

Jonas Sch&#228;fer
Jonas Sch&#228;fer

Reputation: 20718

Short answer: No, you cannot.

Long answer: Well, you can, but then it is not python anymore.

The complex literals are handled when parsing python. They are a well-integrated part of the python language with custom syntax. You cannot simply define your own custom syntax in python. It requires to modify your python parser, which is not an easy task I’m afraid. Also, your program would then be incompatible to other python implementations.

There have been efforts to allow users to define custom string literals (such as in C++) before, however, it never gained traction, as you could simply make the user from myquaternionlibrary import q and then use q("1 + 2j + 3k + 4h"), which is only two characters more than a custom string literal. You would implement q to parse the quaternion from a string.

The third and most tedious way would be to attempt to get Quaternions integrated in the python language. This would require to post on python-ideas (and do some research beforehands to see whether it has been discussed before and how the discussion evolved; include that in your initial discussion to prevent your thread from dying quickly) to see if your suggestions gains traction. Then follows writing a PEP and getting it approved, along with an implementation in the CPython python implementation.

(The last paragraph is basically what I figured out from reading python-ideas for a few years now, it may not be the officially documented process as I might miss some nuances or steps.)

Upvotes: 2

Related Questions