PyBind11 Template Class of Many Types - class

I'd like to use PyBind11 to wrap a specialized array class. However, the array is available in many flavours (one per each plain-old-datatype). The code looks like this:
py::class_<Array2D<float>>(m, "Array2Dfloat", py::buffer_protocol(), py::dynamic_attr())
.def(py::init<>())
.def(py::init<Array2D<float>::xy_t,Array2D<float>::xy_t,float>())
.def("size", &Array2D<float>::size)
.def("width", &Array2D<float>::width)
.def("height", &Array2D<float>::height)
//...
//...
The only way I've thought of to tell PyBind11 about these classes is by duplicating the above for each POD through the use of a very large macro.
Is there a better way to do this?

You can avoid using macros and instead go with a templated declaration function:
template<typename T>
void declare_array(py::module &m, std::string &typestr) {
using Class = Array2D<T>;
std::string pyclass_name = std::string("Array2D") + typestr;
py::class_<Class>(m, pyclass_name.c_str(), py::buffer_protocol(), py::dynamic_attr())
.def(py::init<>())
.def(py::init<Class::xy_t, Class::xy_t, T>())
.def("size", &Class::size)
.def("width", &Class::width)
.def("height", &Class::height);
}
And then call it multiple times:
declare_array<float>(m, "float");
declare_array<int>(m, "int");
...

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.

How to initialize a static dictionary property in a Powershell class?

Is there any way for a static property in a Powershell class to contain a generic dictionary? Without the initialisation syntax that exists in C#, I haven't found a way to do it.
enum Environment
{
Production
QA
Dev
}
class Config
{
# How to get this populated?
static [System.Collections.Generic.Dictionary[Environment, hashtable]] $EnvData
}
Potential workarounds:
Add-Type and a C# class
A GetEnvData() method
Is there a better way I haven't thought of?
Just like in C#, you can use the static constructor (which is what initializers are syntactic sugar for, anyway):
class Config
{
static [System.Collections.Generic.Dictionary[Environment, hashtable]] $EnvData
static Config() {
$d = New-Object ([System.Collections.Generic.Dictionary[Environment, hashtable]])
$d["Production"] = #{Setting="Foo"}
[Config]::EnvData = $d
}
}
The use of a local is not strictly required, but I sleep better knowing the initialization is atomic.
You can also use an initializer ($EnvData = ...) but that's a little tricky in this case, since creating a generic Dictionary in one statement is, well, awkward, and the class syntax doesn't like it if you get complicated (pipes, nested function calls). You could still, if you so wanted, split off initialization into a separate hidden static function and call that for initialization (... $EnvData = [Config]::initialEnvData()), which may be more readable than one big constructor if you've got many conceptually independent properties.

In Haxe (JS Target) is there a way to make static members available to another class as if it was its own?

I have this Haxe class that is growing quite large. It consists mostly of static methods & properties. (It's a module set to compile as JS target).
I would like to separate some of the complex static functions into another class.
Is there any way to mark it with a metatag / indicate the other class is an "extension" to the original class?
Something like #:native("OriginalClass") class OtherClass {...}
The goal is to avoid having to write the full variable access (ex: OriginalClass.LOG_QUEUE vs. LOG_QUEUE) or clutter the imports with each OriginalClass's static methods / properties used at the top of the OtherClass. Basically, something to make it aware that it "is" using the same members as the OriginalClass (whenever an 'undefined' one is found, at compile-time).
Example:
If OriginalClass has static var LOG_QUEUE:Array<String>; then OtherClass would be aware that any usage of LOG_QUEUE compiles to this JS code OriginalClass.LOG_QUEUE
Alright, got a solution after discussing with Dima Granetchi from the Haxe experts group on Slack.
Now, although this will still generate the OtherClass that makes use of the OriginalClass's static members, you can cut down on the quantity of import statements for most (if not all) of the module/class's static members by using the wildcard * symbol, like in this example:
// OriginalClass.hx
package somePackage;
class OriginalClass {
public static var LOG_QUEUE:Array<String>;
public static function main() {
LOG_QUEUE = [];
OtherClass.doSomething();
}
public static function doSomethingOriginal() {
LOG_QUEUE.push("World!");
}
}
// OtherClass.hx
import somePackage.OriginalClass.*; // <-- Demonstrating the WILDCARD (*) symbol
class OtherClass {
public static function doSomething() {
LOG_QUEUE.push("Hello"); //Resolved to OriginalClass.LOG_QUEUE
doSomethingOriginal(); //Resolved to OriginalClass.doSomethingOriginal()
}
}
Although this is a minimal example, it becomes more useful when you have a few different dozen static members used in your OtherClass.
Note
TypeDefs defined in the OriginalClass used inside the OtherClass doesn't seem to get recognized/resolved (may be due to missing public accessor, but I was unable to set it on my typedefs). You can always import those specific TypeDefs with individual import statements, like so:
//Somewhere at the top of OtherClass.hx...
import somePackage.OriginalClass.MyTypeDef;

Kotlin: using google-guava static methods as extensions

Is it possible to use existing java static methods as extensions from the box?
Lets consider com.google.common.collect.Iterables.transform. Now, because I don't know how to deal with this, to use proposed method as the extension, I have to write something like:
import com.google.common.collect.Iterables.transform
public fun <F, T> Iterable<F>.transform(function: Function<in F, out T>) : Iterable<T> {
return transform(this, function);
}
So, after this I could use it with iterables:
Iterable<A> input;
Function<A, B> function;
Iterable<B> output = input.transform(function);
But I think that declaring extension myself is unnecessary. How to omit this declaration?
Update
My question has two main subquestions:
Is it possible to import existing (static) methods as extensions?
No, for now it isn't possible.
How to reuse existing guava's Functions, e.g. to transform Iterables?
Instead of transform you should use map extension, as proposed in answers. To reuse Functions it is possible to use extension like this:
public fun <T, R> Function<T, R>.asFun(): (T) -> R
= { input -> apply(input) };
You shouldn't bring Guava's workarounds for Java into Kotlin. Such API is already a part of Kotlin runtime. So you can write:
val input = listOf(1,2,4,8)
val output = input.map { /*transform function*/ it + 1 }
http://kotlinlang.org/api/latest/jvm/stdlib/kotlin/map.html
All others you can easily discover in IDE's suggestions

Timer Thread with passed Function* and Param

I'm working on finishing up my server for my first iPhone application, and I want to implement a simple little feature.
I would like to run a function (perhaps method as well), if another function returns a certain value after a certain waiting period. Fairly simple concept.... right?
Here's my basic foundation.
template <typename T,class TYP>
struct funcpar{
T (*function)(TYP);
TYP parameter;
funcpar(T (*func)(TYP),TYP param);
funcpar& operator=(const funcpar& fp);
};
The goal here is to be able to call funcpar::function(funcpar::parameter) to run the stored function and parameter, and not have to worry about anything else...
When I attempted to use a void* parameter instead of the template, I couldn't copy the memory as an object (because I didn't know what the end object was going to be, or the beginning for that matter) and when I tried multiple timers, every single object's parameter would change to the new parameter passed to the new timer... With the previous struct I have a
question:
Is it possible to make an all-inclusive pointer to this type of object inside a method of a class? Can I templatize a method, and not the whole class? Would it work exactly like a function template?
I have a managing class that holds a vector of these "jobs" and takes care of everything fairly well. I just don't know how to use a templatized function with the struct, or how to utilize templates on a single method in a class..
I'm also utilizing this in my custom simple threadpool, and that's working fairly well, and has the same problems...
I have another question:
Can I possibly store a function with a parameter before it's run? Something like toRun = dontrunmeyet(withThisParameter);? Is my struct even necessary?
Am I going about this whole thing incorrectly?
If this is overly ambiguous, I can set you up with my whole code for context
In order to create a class method that takes a template parameter, yes, it would work almost exactly like a function template. For example:
class A
{
public:
template<typename T>
void my_function(const T& value) { }
};
int main()
{
A test;
test.my_function(5);
return 0;
}
Secondly, for your structure, you can actually turn that into a functor-object that by overloading operator(), lets you call the structure as-if it were a function rather than having to actually call the specific function pointer members inside the structure. For instance, your structure could be re-written to look like this:
#include <iostream>
template <class ReturnType, class ParameterType>
class funcpar
{
private:
ReturnType (*function)(ParameterType);
ParameterType parameter;
public:
funcpar(ReturnType (*func)(ParameterType),ParameterType param):
function(func), parameter(param) {}
funcpar& operator=(const funcpar& fp);
//operator() overloaded to be a function that takes no arguments
//and returns type ReturnType
ReturnType operator() ()
{
return function(parameter);
}
};
int sample_func(int value)
{
return value + 1;
}
int main()
{
funcpar<int, int> test_functor(sample_func, 5);
//you can call any instance of funcpar just like a normal function
std::cout << test_functor() << std::endl;
return 0;
}
BTW, you do need the functor object (or your structure, etc.) in order to bind a dynamic parameter to a function before the function is called in C/C++ ... you can't "store" a parameter with an actual function. Binding a parameter to a function is actually called a closure, and in C/C++, creating a closure requires a structure/class or some type of associated data-structure you can use to bind a function with a specific parameter stored in memory that is used only for a specific instance of that function call.