Reputation:
I'd like to know if there is a way to define a operation that isn't built into Python - rather than creating some member function of an object and calling it.
For example, define an "absolute value" operation for a class C
, then invoke it as |C|
.
If not, I know it's possible to import operations (I think abs val is in math), so could I look up the tags for operations I import? By "tag" I mean what would replace eq
in def __eq__(self):
or is there no "tag" for imported operations?
Upvotes: 0
Views: 51
Reputation: 35998
Python's syntax is defined by the interpreter's implementation. You cannot add your own syntax without modifying it.
Unless you somehow manage to "preprocess" the source into the "normal" form before it reaches the interpreter.
You may have some luck with PyPy where the interpreter is implemented in Python itself. You need to make a separate unit of "normal" code that would
Do note that your proposed construct will need to be parsed and thus be distinguishable from other language constructs. Your |x|
is, at first sight, indistinguishable from the |
operator (bitwize OR).
Upvotes: 2
Reputation: 91017
If I understand, you want to add something to the already existing "mappings" , such as
+ --> __add__
& --> __and__
etc.?
Then I have to disappoint you - you cannot define such a thing as
|...| --> __abs__.
Upvotes: 1