<p>What mechanisms could languages use to detect certain methods and handle them specially?</p>
<p>For example, in Python, special methods are named differently, using double underscores:</p>
<pre class="lang-python prettyprint-override"><code>def __add__(self, other): ...
</code></pre>
<p>What other ways are there?</p>

<language-design><language-comparison>
What are the different ways of implementing special methods?
CC BY-SA 4.0
2023-06-04T12:02:34.057Z
What do you mean by "implementing" here? Generally it's the user's job to implement these methods, since they exist to allow user-defined behaviour for other parts of the language.
kaya3
CC BY-SA 4.0
2023-06-04T12:04:20.210Z
@kaya3 I mean implementing special methods. How language understand that method is special. For example this method should calls when you are adding it to other object.
чистов_n
CC BY-SA 4.0
2023-06-05T09:17:29.037Z
What's wrong, why down votes?
чистов_n
CC BY-SA 4.0
2023-07-18T12:27:49.453Z
What do you mean by 'special'? Built-in? Intrinsics?
Pablo H
<h1>As a separate table</h1>
<p>Lua's solution to this problem is <a href="https://www.lua.org/pil/13.html" rel="nofollow noreferrer">Metatables</a> which the base table references.</p>
<p>These Metatables are themselves tables containing all the special methods for whatever it is attached to (via a special method).</p>
<p>Additionally, Lua prefixes &quot;Metamethods&quot; with <code>__</code>, eg. <code>__add</code>, which prevents collisions when using Metatables as regular tables a well, a trick often used to implement classes.</p>

CC BY-SA 4.0
2023-06-06T23:57:30.663Z
2023-06-06T23:57:30.663Z
ATaco
<p>Various languages introduce special syntax to disambiguate their own special affordances (or even internalities) from similar regular names by the user in user-space, based on the notion that both use the same language construct. Like C/C++ &quot;reserved&quot; <code>__</code> preprocessor directives present themselves being not conceptually different from other user-defined preprocessor directives, just these with <code>__</code> are built-in or reserved for the compiler, etc. Could be the same with functions, classes, and so on. Sometimes, these special affordances are not formally reserved/defined in the language spec, and it's just a convention, also allowing implementers, tool-makers (and also users, if they want to or need to and accept the potential risks), etc. to add their things using this special convention. Maybe sometimes not all of these might be present or implemented in the same way in different environments.</p>
<p>Similar to abel1502's answer, there's the other school of design, which is not in favor of polluting/reducing the user-space of names with special/reserved names. Especially in languages which do not make heavy use of lots of special symbols with special meanings, and instead follow the idea that one has a small language &quot;core&quot; of a few reserved keyword names for a few constructs, and everything else is constructed by using/combining these constructs. So the other option is to just make these a regular function or constant or preprocessor directive that's part of the standard library or provided as such among the set of implementer/compiler functions - why should these &quot;special&quot; constructs need to be syntactically or naming-convention-wise be different from a math or file system access function? Or there might be just a function with a fixed name that takes a string as an argument, to request values/settings from the internal representation (as also is often already the case in many languages). Or if really unavoidable, have one special keyword or namespace to put these constructs under, so users remain free of using any names, don't run the risk of conflicting with reserved/special naming conventions, and there's less different styles of notation if encountering these things for the first time, wondering where these come from (is it from a third-party module, where is it defined, how do these just magically work, but are not among the language's keywords? How to look these up per search?).</p>

CC BY-SA 4.0
2024-06-15T00:19:38.007Z
2024-06-15T00:19:38.007Z
skreutzer
<p><strong>Special things require special markers.</strong></p>
<p>That's the only thing that really matters. As long as your language has some easy way to differentiate a special method from a regular one, and that marker shows up early enough in parsing to resolve potential ambiguities, that is sufficient.</p>
<p>But to answer the question as intended, here are a few examples:</p>
<ul>
<li>Special name. Python does this.</li>
<li>Special keyword. C# does this with getters and setters.</li>
<li>Special syntax.</li>
<li>Or any combination of the above. C++ and Swift do this with operators.</li>
</ul>

CC BY-SA 4.0
2023-06-04T16:08:05.410Z
2023-06-04T19:24:29.140Z
2023-06-04T19:24:29.140Z
Gavin D. Howard
CC BY-SA 4.0
2023-06-04T18:31:05.080Z
Not sure about "early enough in parsing" ─ in Python's case, these methods don't have any special status until runtime when they're looked up on the class. They don't have to be distinguished at parse-time, and can even be implemented dynamically by generating methods at runtime with the correct names.
kaya3
CC BY-SA 4.0
2023-06-04T19:05:25.770Z
Unlike C++, which models calls with an operator (`operator()`), Swift models calls with the method `callAsFunction`. I'm not quite sure why they made that decision, but given that operators are just static functions whose names aren't valid identifiers (e.g. `static func +(lhs:rhs:)`), trying to have a `static func()` might cause some parsing ambiguities.
Bbrk24
CC BY-SA 4.0
2023-06-04T19:23:42.110Z
@kaya3, sorry for the poor wording. Bbrk24 got my intention right: I meant resolving ambiguities. I'll update my answer.
Gavin D. Howard
CC BY-SA 4.0
2024-06-15T21:37:29.557Z
In Python's case, `__XXX__` is just a naming convention. The parser doesn't treat them specially. Rather, the parser treats the `+` operator specially and translates it into a call to the `__add__()` method (I'm simplifying).
Barmar
CC BY-SA 4.0
2024-06-16T16:00:32.363Z
Empty interfaces and/or attributes. For example, empty interfaces that instruct the compiler to work that class differently. This is a form of *normal* syntax and *normal* names (as these empty interfaces/atributes are declared normally in compiler source).
André L F S Bacci
CC BY-SA 4.0
2024-06-19T08:48:07.717Z
Some examples might be helpful here
CoffeeTableEspresso
<p>There's also Haskell's approach, which is to make them (mostly) not special in the first place.</p>
<p>I'm going to use comparison as my example, because the addition operation is a little bit quirky in Haskell, and many feel that arithmetic needs to be cleaned up.</p>
<p>If you want to make a type comparable, you make it a member of the class <code>Ord</code>:</p>
<pre class="lang-haskell prettyprint-override"><code>data Foo = Foo Int

instance Ord Foo where
    comparing (Foo x) (Foo y) = comparing x y
</code></pre>
<p>Operators such as <code>&lt;=</code> are defined in terms of <code>comparing</code>, so now you can just compare two <code>Foo</code> values and it all works.</p>
<p>This relies on several interacting language and compiler features:</p>
<ul>
<li>&quot;Built in&quot; operations like comparison are generic by default, and basic operations are handled by intrinsic functions. This is the only sense in which operations like addition and comparison are &quot;special&quot;.</li>
<li>You do not need to declare a type to be a member of a class at the point where the <em>type</em> is declared; you can do it anywhere.</li>
<li>Aggressive specialisation and inlining optimisations to compile away any layers of abstraction (e.g. to get from <code>&lt;=</code>, through <code>comparing</code>, to the underlying intrinsic function).</li>
</ul>
<p>As a programmer, you would very much like a comparison on word-sized integers to compile down to one instruction. Intrinsic functions is one way to achieve this.</p>
<p>The second point is what makes the system ergonomic. In a typical Simula-style programming language, the only place where you can declare a type to be a member of a class is at the point where the type is declared.</p>
<p>A declaration like this:</p>
<pre class="lang-java prettyprint-override"><code>class Foo extends Comparable
{
}
</code></pre>
<p>...means three distinct things.</p>
<ol>
<li>It declares a new data type <code>Foo</code>.</li>
<li>It declares a new class <code>Foo</code>, and declares it to be a subclass of <code>Comparable</code>.</li>
<li>It declares that the type <code>Foo</code> is a member of the class <code>Foo</code>.</li>
</ol>
<p>Haskell keeps types and classes distinct, so you can declare a type to be a member of a class anywhere.</p>

CC BY-SA 4.0
2023-06-07T00:01:33.147Z
2023-06-07T00:01:33.147Z
Pseudonym
<p>I haven't seen this approach used anywhere, but in my language method (and attribute) names aren't limited to being strings. Essentially, any hashable and comparable object is allowed, with the syntax of <code>foo.(bar)</code> (whrere <code>bar</code> must be a valid expression resulting in an acceptable object). <code>foo.bar</code> is the equivalent of <code>foo.(&quot;bar&quot;)</code>, in particular. With this representation, special methods (and special attributes in general) can be named with dedicated key-objects, like <code>foo.(std::add)</code>. This has a very nice benefit of simultaneously avoiding name collisions and allowing to introduce user-defined special attributes (whereas with Python's approach you would risk conflicting with either someone else's special attributes, or a newer language version).</p>

CC BY-SA 4.0
2023-06-06T20:30:32.820Z
2023-06-06T20:30:32.820Z
abel1502
CC BY-SA 4.0
2023-06-06T21:15:27.750Z
JavaScript works like this. `x.y` is a shorthand for `x["y"]`, and everything being a hash table means anything can be used as key. Then [unique symbols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) can be used to make "special" members (eg. `obj[Symbol.iterator]`).
Longinus
# What are the different ways of implementing special methods?
Posted by: username_0 on 2023-06-04
What mechanisms could languages use to detect certain methods and handle them specially?
For example, in Python, special methods are named differently, using double underscores:
def __add__(self, other): ...

What other ways are there?
**Tags:** language-design language-comparison
> **Comments:**
> **username_1**: What do you mean by "implementing" here? Generally it's the user's job to implement these methods, since they exist to allow user-defined behaviour for other parts of the language.  
> **username_0**: @kaya3 I mean implementing special methods. How language understand that method is special. For example this method should calls when you are adding it to other object.  
> **username_0**: What's wrong, why down votes?  
> **username_2**: What do you mean by 'special'? Built-in? Intrinsics?  
---
## 5 answers
### Answer by username_5 on 2023-06-04. Score: 8 | Accepted answer
**Special things require special markers.**

That's the only thing that really matters. As long as your language has some easy way to differentiate a special method from a regular one, and that marker shows up early enough in parsing to resolve potential ambiguities, that is sufficient.

But to answer the question as intended, here are a few examples:

* Special name. Python does this.
* Special keyword. C# does this with getters and setters.
* Special syntax.
* Or any combination of the above. C++ and Swift do this with operators.
> **Comments:**
> **username_1** (2023-06-04): Not sure about "early enough in parsing" ─ in Python's case, these methods don't have any special status until runtime when they're looked up on the class. They don't have to be distinguished at parse-time, and can even be implemented dynamically by generating methods at runtime with the correct names.  
> **username_6** (2023-06-04): Unlike C++, which models calls with an operator (`operator()`), Swift models calls with the method `callAsFunction`. I'm not quite sure why they made that decision, but given that operators are just static functions whose names aren't valid identifiers (e.g. `static func +(lhs:rhs:)`), trying to have a `static func()` might cause some parsing ambiguities.  
> **username_5** (2023-06-04): @kaya3, sorry for the poor wording. Bbrk24 got my intention right: I meant resolving ambiguities. I'll update my answer.  
> **username_7** (2024-06-15): In Python's case, `__XXX__` is just a naming convention. The parser doesn't treat them specially. Rather, the parser treats the `+` operator specially and translates it into a call to the `__add__()` method (I'm simplifying).  
> **username_8** (2024-06-16): Empty interfaces and/or attributes. For example, empty interfaces that instruct the compiler to work that class differently. This is a form of *normal* syntax and *normal* names (as these empty interfaces/atributes are declared normally in compiler source).  
> **username_9** (2024-06-19): Some examples might be helpful here  
---
### Answer by username_10 on 2023-06-07. Score: 5
There's also Haskell's approach, which is to make them (mostly) not special in the first place.
I'm going to use comparison as my example, because the addition operation is a little bit quirky in Haskell, and many feel that arithmetic needs to be cleaned up.
If you want to make a type comparable, you make it a member of the class Ord:
data Foo = Foo Int

instance Ord Foo where
    comparing (Foo x) (Foo y) = comparing x y

Operators such as <= are defined in terms of comparing, so now you can just compare two Foo values and it all works.
This relies on several interacting language and compiler features:

"Built in" operations like comparison are generic by default, and basic operations are handled by intrinsic functions. This is the only sense in which operations like addition and comparison are "special".
You do not need to declare a type to be a member of a class at the point where the type is declared; you can do it anywhere.
Aggressive specialisation and inlining optimisations to compile away any layers of abstraction (e.g. to get from <=, through comparing, to the underlying intrinsic function).

As a programmer, you would very much like a comparison on word-sized integers to compile down to one instruction. Intrinsic functions is one way to achieve this.
The second point is what makes the system ergonomic. In a typical Simula-style programming language, the only place where you can declare a type to be a member of a class is at the point where the type is declared.
A declaration like this:
class Foo extends Comparable
{
}

...means three distinct things.

It declares a new data type Foo.
It declares a new class Foo, and declares it to be a subclass of Comparable.
It declares that the type Foo is a member of the class Foo.

Haskell keeps types and classes distinct, so you can declare a type to be a member of a class anywhere.
---
### Answer by username_11 on 2023-06-06. Score: 4
I haven't seen this approach used anywhere, but in my language method (and attribute) names aren't limited to being strings. Essentially, any hashable and comparable object is allowed, with the syntax of `foo.(bar)` (whrere `bar` must be a valid expression resulting in an acceptable object). `foo.bar` is the equivalent of `foo.("bar")`, in particular. With this representation, special methods (and special attributes in general) can be named with dedicated key-objects, like `foo.(std::add)`. This has a very nice benefit of simultaneously avoiding name collisions and allowing to introduce user-defined special attributes (whereas with Python's approach you would risk conflicting with either someone else's special attributes, or a newer language version).
> **Comments:**
> **username_12** (2023-06-06): JavaScript works like this. `x.y` is a shorthand for `x["y"]`, and everything being a hash table means anything can be used as key. Then [unique symbols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) can be used to make "special" members (eg. `obj[Symbol.iterator]`).  
---
### Answer by username_3 on 2023-06-06. Score: 2
# As a separate table

Lua's solution to this problem is [Metatables](https://www.lua.org/pil/13.html) which the base table references.

These Metatables are themselves tables containing all the special methods for whatever it is attached to (via a special method).

Additionally, Lua prefixes "Metamethods" with `__`, eg. `__add`, which prevents collisions when using Metatables as regular tables a well, a trick often used to implement classes.
---
### Answer by username_4 on 2024-06-15. Score: 0
Various languages introduce special syntax to disambiguate their own special affordances (or even internalities) from similar regular names by the user in user-space, based on the notion that both use the same language construct. Like C/C++ "reserved" `__` preprocessor directives present themselves being not conceptually different from other user-defined preprocessor directives, just these with `__` are built-in or reserved for the compiler, etc. Could be the same with functions, classes, and so on. Sometimes, these special affordances are not formally reserved/defined in the language spec, and it's just a convention, also allowing implementers, tool-makers (and also users, if they want to or need to and accept the potential risks), etc. to add their things using this special convention. Maybe sometimes not all of these might be present or implemented in the same way in different environments.

Similar to abel1502's answer, there's the other school of design, which is not in favor of polluting/reducing the user-space of names with special/reserved names. Especially in languages which do not make heavy use of lots of special symbols with special meanings, and instead follow the idea that one has a small language "core" of a few reserved keyword names for a few constructs, and everything else is constructed by using/combining these constructs. So the other option is to just make these a regular function or constant or preprocessor directive that's part of the standard library or provided as such among the set of implementer/compiler functions - why should these "special" constructs need to be syntactically or naming-convention-wise be different from a math or file system access function? Or there might be just a function with a fixed name that takes a string as an argument, to request values/settings from the internal representation (as also is often already the case in many languages). Or if really unavoidable, have one special keyword or namespace to put these constructs under, so users remain free of using any names, don't run the risk of conflicting with reserved/special naming conventions, and there's less different styles of notation if encountering these things for the first time, wondering where these come from (is it from a third-party module, where is it defined, how do these just magically work, but are not among the language's keywords? How to look these up per search?).
---
