IronLanguages / ironpython3

Implementation of Python 3.x for .NET Framework that is built on top of the Dynamic Language Runtime.
Apache License 2.0
2.51k stars 290 forks source link

Add "how-to" documentation for extending IronPython with a C# module #1686

Open minesworld opened 1 year ago

minesworld commented 1 year ago

Task: create a python module containing classes

E.g. behaves like a built-in StdLib module.

At the moment I subclass PythonModuleand add an instance to the engines language context via PublishModule(name, instance). But this way I can not add a static class definition of a PythonModule. Also Python code can access all members of the module added this way.

After looking into the IronPython3 sources I neither unstand how that PythonModule assembly declaration magic works nor how I can use this magic on my own and import them via code which seems to be "internal" only as CreateBuiltinModule() ... .

The use case for a good behaving Python module written in C# are manifold - but for me its the main feature of using IronPython as a scripting language: to NOT use import clr and NOT using C# classes and syntax... . Which does not seem to work if the module is not a seperate .dll ...

In case of multi language libraries it makes sense to wrap the C# implementation into a real Python module in a way that Python source using it does not to be changed at all. There are cases were this is the ONLY option as the native Python implementation uses a syntax not implemented by IronPython yet...

The IronPython documentation about extending looks like copy&paste from CPython and doesn't help at all. And even for me as someone who has some knowledge of CPython internals, looking at IronPython sources is a little bit "confusing" as it is a total different "beast"...

For every IronPython user giving their appplications end users well known Python syntax for a library is a feature whose value should be top priority .

Best way would be a working example project which:

As not having this documentation available wastes every programmers time it would be nice (if possible) to provide a link to an article, video etc. ASAP were this is shown until the "real solution" is there. The only one I found was a presentation which was cancelled...

BCSharp commented 1 year ago

The codebase contains some sample code that perhaps addresses most of your questions: a sample module xxsubtype.

I see that it uses a few (nonessential) internal methods, so perhaps it would be good to clean it up sake the sake of example. Also, it is compiled into IronPython.Modules.dll, so it can be imported without any configuration. If you create your own DLL with your own Python modules, e.g. MyModules.dll, then, as usual, you need to clr.AddReference('MyModules').