roxygen2 docstrings for Reference Classes overriding base class - roxygen2

I have an abstract base class that looks like this:
#' An Abstract Base Class
Filter <- setRefClass(
Class = "Filter",
methods = list(
train = function(x) {
"Override this method to train any associated parameters for the filter on the supplied data"
print("no learning to be done")
})
)
and the following class that extends this class:
#' Filter class that leverages the prcomp R method.
PcaFilter <- setRefClass(
"PcaFilter",
contains="Filter",
fields=list(
d="numeric",
model="ANY"
),
methods=list(
train=function(x) {
"train PCA model, store result to model attribute of obj"
model <<- prcomp(x)
})
)
After I run
roxygen2::roxygenize()
Then I get two man files but in the man file for the second class the docstring for the overridden class does not come through- I get the docstring for the base class. Am I doing something wrong or is this a bug with roxygen2 ?
Also is there any better way of doing this? I would like to be able to use multi-line docstrings.

Having searched through the Issues on the roxygen github repo. Found that there's already an active Issue pertaining to this:
https://github.com/klutometis/roxygen/issues/433
In summary: the support and documentation for Reference Classes in roxygen is not great as of v5.0. The suggested method is still to use docstrings and it's impossible to override the docstrings of parents.

Related

Python C API - How to inherit from your own python class?

The newtypes tutorial shows you how to inherit from a base python class. Can you inherit from your own python class? Something like this?
PyObject *mod = PyImport_AddModule("foomod");
PyObject *o = PyObject_GetAttrString(mod, "BaseClass");
PyTypeObject *t = o->ob_type;
FooType.tp_base = t;
if (PyType_Ready(&FooType ) < 0) return NULL;
though you need to define your struct with the base class as the first member per the documentation so it sounds like this is not possible? ie how would I setup the Foo struct?
typedef struct {
PyListObject list;
int state;
} SubListObject;
What I'm really trying to do is subclass _UnixSelectorEventLoop and it seems like my only solution is to define a python class that derives from my C class and from _UnixSelectorEventLoop with my C class listed first so that it can override methods in the other base class.
I think you're basically right on your assessment:
it seems like my only solution is to define a python class that derives from my C class and from _UnixSelectorEventLoop with my C class listed first so that it can override methods in the other base class.
You can't define a class that inherits from a Python class because it'd need to start with a C struct of basically arbitrary size.
There's a couple of other options that you might like to consider:
You could create a class the manual way by calling PyType_Type. See this useful answer on a question about multiple inheritance which is another sort of inheritance that the C API struggles with. This probably limits you too much, since you can't have C attributes, but you can have C functions.
You could do "inheritance by composition" - i.e. have you _UnixSelectorEventLoop as part of the object, then forward __getattr__ and __setattr__ to it in the event of unknown attributes. It's probably easier to see what I mean with Python code (which is simply but tediously transformed into C API code)
class YourClass:
def __init__(self,...):
self.state = 0
self._usel = _UnixSelectorEventLoop()
def __getattr__(self, name):
return getattr(self._usel, 'name')
def __setattr__(self, name, value):
if name in self.__dict__:
object.__setattr__(self, name, value)
else:
setattr(self._usel, name, value)
# maybe __hasattr__ and __delattr__ too?
I'm hoping to avoid having to write this C API code myself, but the slots are tp_getattro and tp_setattro. Note that __getattr__ will need to be more comprehensive in the C version, since it acts closer to the __getattribute__ in Python. The flipside is that isinstance and issubclass will fail, which may or may not be an issue for you.

Better way to do class type alias?

From time to time, I would like to call a class differently depending on the context or to reduce duplication.
Let's assume, I have the following classes defined:
// in file a.dart
class A {
final String someprop;
A(this.someprop)
}
// in file b.dart
abstract class BInterface {
String get someprop;
}
class B = A with EmptyMixin implements BInterface;
For this syntax to check out, I have to define EmptyMixin so that the syntax is OK.
Do you know of a better/prettier way to do this "aliasing" in Dart?
I'm afraid the way you're doing it is the prettiest way to do this at the moment. There is a very old, but still open and active issue: https://github.com/dart-lang/sdk/issues/2626 that proposes the typedef B = A; syntax for aliasing types.

Scala - unbound wildcard exception (Play Framework 2.3 Template)

I am using Play Framework 2.3 I am using the scala template engine to create my views and Java elsewhere.
My model extends an abstract parameterised object like so... (pseudo code)
Abstract object:
public abstract class MyObject<T> {
// various bits
public class MyInnerObject {
// more stuff
}
}
Model object (singleton)
public class SomeModel extends MyObject<SomeBean> {
public static SomeModel getInstance() {
if (instance == null)
instance = new SomeModel();
return instance;
}
// more bits
}
I then pass the model to the view from another view helper:
#MyHelper(SomeModel.getInstance())
MyHelper scala view template:
#*******************************************
* My helper
*******************************************#
#(myObj: some.namespace.MyObject[_])
#import some.namespace.MyObject
#doSomething(myInnerObj: MyObject[_]#MyInnerObject) = {
#* do some stuff *#
}
#for(myInnerObj <- myObj.getInnerObjects()) {
#doSomething(myInnerObj)
}
However I get an error on the line #doSomething(myInnerObj: MyObject[_]#MyInnerObject) stating
unbound wildcard exception
I am not sure the correct Scala syntax to avoid this error I had naively assumed that I could use the _ to specify arbitrary tyope but it won't let me do this.
What is the correct syntax?
UPDATE 1
Changing the method definition to:
#doSomething[T](myInnerObj: MyObject[T]#MyInnerObject)
gives further errors:
no type parameters for method doSomething: (myInnerObj:[T]#MyInnerObject)play.twirl.api.HtmlFormat.Appendable exist so that it can be applied to arguments (myObj.MyInnerObject)
--- because ---
argument expression's type is not compatible with formal parameter type;
found : myObj.MyInnerObject
required: MyObject[?T]#MyInnerObject
It would seem that the Twirl templating engine does not support this syntax currently, although I'm not 100% sure.
I can solve the problem by removing the doSomething method completely...
#*******************************************
* My helper
*******************************************#
#(myObj: some.namespace.MyObject[_])
#import some.namespace.MyObject
#for(myInnerObj <- myObj.getInnerObjects()) {
<div>#myInnerObj.getSomeProperty()</div>
}
But I am bout 10% happy with the solution... It works at least but it feels very restricting that I cannot delegate to methods to help keep my code maintainable. By the look of the comments the problem seems to be a limitation in Twirl, not allowing type arguments for functions in views.
Note: I have accepted this answer as it removes the original problem of the exception however this is only because the solution I want doesn't exist... yet.

Polymorphism in Object construction

I want to create specific Object according to the type argument.
Pseudo code looks like this.
sub new {
my $type = shift;
if($type eq "S1") {$interface = X->new(); }
if($type eq "S2") {$interface = Y->new(); }
etc...
return $interface;
}
Options might be:
Substitute "package" name with $type argument. Requires package name coordination with $type.
Use Hash{S1 => X} in the Master constructor to select Value according to $type passed. Requires Hash maintenance when adding new
Object types.
I don't like any of above. Looking trully polimorphic way to accomplish that.
Thank You,
k
Your best option would likely be to use a factory pattern. A factory method takes the parameters for creating an instance of your class, then decides which object to instantiate and return from that. This can also make dependency injection easier for testing.
You'd probably be looking at something like this (in Java-esque code), with an employee object:
public class EmployeeFactory
{
public static create(String type)
{
switch (type) {
case type1:
return new EmployeeTypeOne();
case type2:
return new EmployeeTypeTwo();
default:
throw new Exception("Unrecognized type");
}
}
}
Your employees would inherit from a common interface or abstract class. You can use the factory to handle constructor parameters as well if you prefer, just try to keep things fairly reasonable (don't pass a million parameters - the factory should internally handle complex objects)
See http://refactoring.com/catalog/replaceConstructorWithFactoryMethod.html for more information.
You might like Module::PluginFinder for that. Create all your specific types in a specific namespace and give them each some identifying (constant? sub?) that the main dispatcher will then use to identify which class handles a given type.

anybody doing a class tree in Dart?

Darts Mirrors are for me currently poorly documented and very difficult to experiment with - they behave differently in code than from within the console.
for my own use, I would love to be able to treat classes (Types) as a trees, with a node being something like:
class Node {
type ... <== Type itself
name ... <== name of current class
super ... <== super of this class, eg, extends super
mixins ... <== mixins used to build this Type
extendChildren ... <== Types for which this type is super
mixinChildren ... <== Types for which this type is a mixin
}
for the life of me, I cannot get something this basic out of current Mirrors. hoping that somebody smarter than me has given it a shot!!
Below is a simple example which prints the name of the superclass and the name of Foo's members.
Note that the API uses Symbols, not strings. These are required so that dart2js can minify code that uses mirrors, they're a bit of a pain, but they mean that your code will run cross browser, and be compact.
To convert between symbols and strings see MirrorSystem.getName() and MirrorSystem.getSymbol() (Actually I believe you can just use new Symbol('foo') now).
Also note a new feature was recently added giving a special literal syntax for symbols. Up until recently you needed to type const Symbol('foo'), now just #foo, you may see a mix of old an new when looking at examples.
See this article for more information about mirrors.
Warning - probably a few typos in the example.
import 'dart:mirrors';
class Bob {
}
class Foo extends Bob {
String bar = 'jim';
}
main() {
var classMirror = reflectClass(Foo);
print(MirrorSystem.getName(classMirror.superClass.simpleName));
classMirror.declarations.values.forEach((d) => print(MirrorSystem.getName(d.simpleName)));
}
Update: Based on what Alan said below (Also untested):
Example source:
library foo;
class B extends A {
}
class A {
}
Definition:
List<ClassMirror> findSubClasses(Symbol libraryName, ClassMirror superClass) =>
currentMirrorSystem().findLibrary(libraryName).declarations.values
.where((d) => d is ClassMirror
&& d.superClass.simpleName == superClass.simpleName);
Usage:
var cm = reflectClass(A);
var subclasses = findSubClasses(#foo, cm);
There is a #MirrorsUsed attribute that you may want to experiment with if you're interested on compiling to js. It's still experimental so expect this to change.