• Stars
    star
    1,293
  • Rank 36,391 (Top 0.8 %)
  • Language
    Nim
  • License
    MIT License
  • Created about 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Nim - Python bridge

nimpy Build Status

Native language integration with Python has never been easier!

Implementing a Python Module in Nim

# mymodule.nim - file name should match the module name you're going to import from python
import nimpy

proc greet(name: string): string {.exportpy.} =
  return "Hello, " & name & "!"
# Compile on Windows:
nim c --app:lib --out:mymodule.pyd --threads:on --tlsEmulation:off --passL:-static mymodule
# Compile on everything else:
nim c --app:lib --out:mymodule.so --threads:on mymodule
# test.py
import mymodule
assert mymodule.greet("world") == "Hello, world!"
assert mymodule.greet(name="world") == "Hello, world!"

Calling Python From Nim

import nimpy
let os = pyImport("os")
echo "Current dir is: ", os.getcwd().to(string)

# sum(range(1, 5))
let py = pyBuiltinsModule()
let s = py.sum(py.range(0, 5)).to(int)
assert s == 10

Note: here nimpy relies on your local python installation.

Importing Nim Extensions Directly

For a convenient way to import your Nim extension modules directly, you can use Nimporter.

Misc

The library is designed with ABI compatibility in mind. That is the compiled module doesn't depend on particular Python version, it should properly work with any. The C API symbols are loaded in runtime from whichever process has launched your module.

Troubleshooting, Q&A

Importing the compiled module from Python fails

If you're getting ImportError: dynamic module does not define module export function ... make sure that the module you're importing from Python has exactly the same name as the nim file which the module is implemented in.

Nimpy fails to find (proper) libpython

The most reliable way to find libpython is find_libpython python package:

pip3 install find_libpython
python3 -c 'import find_libpython; print(find_libpython.find_libpython())'

Then you can specify path to libpython using nimpy.py_lib.pyInitLibPath. Tracking issue: #171.

Nim strings are converted to Python bytes instead of string

nimpy converts Nim strings to Python strings usually, but since Nim strings are encoding agnostic and may contain invalid utf8 sequences, nimpy will fallback to Python bytes in such cases.

Is there any numpy compatibility?

nimpy allows manipulating numpy objects just how you would do it in Python, however it is not much more efficient. scinim offers API for performance critical numpy interop, and it is advised to consider it first.

Nimpy also exposes lower level Buffer protocol, see raw_buffers.nim. tpyfromnim.nim contains a very basic test for this.

Does nim default garbage collector (GC) and ARC/ORC work?

Yes. nimpy internally does everything needed to run the GC properly (keeps the stack bottom actual, and appropriate nim references alive), and doesn't introduce any special rules on top. So the GC question boils down to proper GC usage in nim shared libraries, you'd better lookup elsewhere. The following guidelines are by no means comprehensive, but should be enough for the quick start:

  • If it's known there will be only one nimpy module in the process, you should be fine.
  • If there is more than one nimpy module, it is recommended to move nim runtime out to a separate shared library. However it might not be needed if nim references are known to never travel between nim shared libraries.
  • If you hit any GC problems with nimpy, whether you followed these guidelines or not, please report them to nimpy tracker :)
Windows, threads and MinGW

When compiling with --threads:on Nim will imply --tlsEmulation:on (Windows only) which prevents Nim runtime from initing properly when being called from a foreign thread (which is always the case in case of Python module).

Adding --tlsEmulation:off when using MinGW toolchain (Nim's default on Windows) will introduce a dependency on libgcc_s_seh-*.dll, that newer python versions are often unable to find.

One way to overcome this is to link with libgcc statically, by passing -static to linker, or --passL:-static to Nim.

Exporting Nim types as Python classes

Warning! This is experimental.

  • An exported type should be a ref object and inherit PyNimObjectExperimental directly or indirectly.
  • The type will only be exported if at least one exported "method" is defined.
  • A proc will be exported as python type method only if it's first argument is of the corresponding type and is called self. If the first argument is not called self, the proc will exported as a global module function.
# mymodule.nim
type TestType = ref object of PyNimObjectExperimental
  myField: string

proc setMyField(self: TestType, value: string) {.exportpy.} =
  self.myField = value

proc getMyField(self: TestType): string {.exportpy.} =
  self.myField
# test.py
import mymodule
tt = mymodule.TestType()
tt.setMyField("Hello")
assert(tt.getMyField() == "Hello")

Future directions

  • High level buffer API

Stargazers over time

Stargazers over time

More Repositories

1

nimx

GUI library
Nim
1,091
star
2

jnim

Nim - Java bridge
Nim
184
star
3

rod

Cross-platform game engine
Nim
136
star
4

nimsl

Shaders in Nim language
Nim
98
star
5

iface

Nim
71
star
6

wasmrt

Nim
64
star
7

variant

Variant type and type matching for Nim
Nim
56
star
8

jsbind

Nim
51
star
9

sound

Cross-platform sound mixer library
Nim
47
star
10

kiwi

Constraint solving library
Nim
45
star
11

nim-sdl-template

Cross-platform SDL/Nim skeleton
Java
45
star
12

asyncthreadpool

Awaitable threadpool for nim
Nim
45
star
13

darwin

Bindings for MacOS/iOS frameworks
Nim
40
star
14

android

Nim
37
star
15

coverage

Code coverage library for Nim
Nim
36
star
16

ecs

Entity Component System
Nim
27
star
17

nimble-tag

22
star
18

threadpools

Nim
21
star
19

yasync

Nim
21
star
20

cassandra

Nim bindings to cassandra db driver
Nim
15
star
21

closure_compiler

Nim binding to closure compiler
Nim
12
star
22

webdriver

Nim webdriver for Chrome and Firefox
Nim
12
star
23

minecraft

Nim
10
star
24

clipboard

Nim
10
star
25

wayland

Nim bindings for wayland
Nim
10
star
26

nim-docker

Auto-built docker image with latest Nim devel version
Shell
10
star
27

emacs

Create emacs modules in nim
Nim
9
star
28

async_http_request

Basic http_request implementation for JS and native targets
Nim
9
star
29

typelists

Typelists in Nim
Nim
9
star
30

clurp

Slurp C libraries into nim packages
Nim
8
star
31

wasmer

Wasmer wrapper - embed wasm in nim
Nim
8
star
32

plists

plist library for Nim
Nim
7
star
33

bicubic-interpolation-image-processing

Automatically exported from code.google.com/p/bicubic-interpolation-image-processing
C
7
star
34

persistent_enums

Define enums which values preserve their binary representation upon inserting or reordering
Nim
5
star
35

asyncssh

High level async libssh2 wrapper
Nim
4
star
36

ddparser

Port of Dparser to D language
C
4
star
37

cassowary.d

Cassowary constraint solving library for D language
D
4
star
38

rect_packer

Pack rects into bigger rect
Nim
4
star
39

ttf

Nim
4
star
40

preferences

Nim
4
star
41

imgtools

Nim
3
star
42

gplay

Google Play APK Uploader
Nim
3
star
43

nimx_nanovg

Nimx + nanovg demo.
Nim
2
star
44

tesseract

Nim
2
star
45

cocoa.d

DLang <-> Objective-C bridge
D
2
star
46

olm

libolm bindings
Nim
1
star
47

nim-chess

Plain chess game, written from scratch, GTK3 GUI with unicode pieces, written in Nim
Nim
1
star
48

wgpu

WebGPU API
C
1
star
49

linktools

Nim
1
star
50

rethinkdb

RethinkDB driver in Nim
Nim
1
star
51

adbclient

Nim
1
star
52

wafli

Nim
1
star
53

dataview

DataView for Nim, like in JS
Nim
1
star
54

vktest

Nim
1
star