coconut
coconut copied to clipboard
Feature: Use name of meta/superclass instead of writing `class <name> (<meta/superclass name>)`
Sometimes you have a bunch of small classes that don't justify all the trouble of writing class
a hundred times. The same could be said for subclasses or a class full of static methods. Can coconut provide the option to use a meta/superclass' name instead of the class
keyword?
Such a feature would be used like so:
# CST for the CST
data Node(name: str): ...
Node Concat(operands: Node[]): ...
Node Union(operands: Node[]): ...
Node Disj(generator: Node, discriminator: Node): ...
# CST
Noun = Union(load_nouns(...))
Verb = Union(load_verbs(...))
...
Sentence = SVO | OVS | SOV
# generate AST
sentence = Sentence.generate(...)
Custom keyword'ed blocks would:
- draw more attention to the actual data structure being used, thus helping the developer think in terms of their own program's structure, rather than strictly thinking in terms of the Python/Coconut semantics
- reduce repetitive keywords and improve code readability
- be convenient
Besides writing generic superclass_name subclass_name: ...
statements, other use-cases would be:
- OOP keywords:
-
meta/metaclass
: declares that a given class is a subclass oftype
meta MakeSerializable: ... # same as class MakeSerializable (type): ...
-
abstract
: declares that a given class is a subclass ofabc.ABC
abstract MyAbstractClass: ... # same as class MyAbstractClass (abc.ABC): ...
-
static
: annotates all methods in the given class asstaticmethods
abstract MyStaticClass: _a = 1 def foo(a, b): ... def bar(): ... def baz(a): ... # same as class MyStaticClass: ... _a = 1 @staticmethod def foo(a, b): ... @staticmethod def bar(): ... @staticmethod def baz(a): ...
-
subclass
: makes the given class a subclass of its containing class; thesubclass
declaration must take place inside another class.
class Super: subclass Sub1: ... subclass Sub2: ... # same as class Super: class Sub1(Super): ... class Sub2(Super): ...
-
private
: you get the idea
-
-
rule
blocks for reactive subgraph rewritingrule find_hydroxyl_group ({'R': Node, 'O': Node('O'), 'H': Node('H')}): return Hydroxyl(R)
- reactive programming constructs (don't ask how):
when x>5: x=0
Alternatives:
- Decorators accomplish the same functionality, but they are not as concise, especially when you have to write hundreds of rules for your biochemistry simulator.
- Directly specify the metaclass. Metaclasses are not as easy to read as when they are buried around subclasses and metaclass kwargs.
- Write a domain specific language. DSL's sacrifice flexibility for speed and clarity. However if the recommended feature is accepted into coconut, developers can have both.