Hi all!
I'm very new to Nim (even didn't get started) and do some "research" on topics I'm most interested in. And my the very noob question is: Is it possible to run existing Python code(bindings) from Nim?
Thank you!
Yes it is. Disclaimer being that I've never done it myself ;)
I have a hunch that someone has made a package for this purpose.
At the minimum you can use Python's C API directly
Maybe have a look at https://github.com/nim-lang/python
This is for Python 2, by the way. Are you using Python 2 or 3?
Glancing though the list I also found this: https://github.com/matkuki/python3
Also, welcome to the Nim community! We're really glad you're joining us :)
Do not forget Yglukhov's great nimpy: https://github.com/yglukhov/nimpy
Thanks for the shout-out twetzel59!
Thank you all for such a warm welcome :)
Unfortunately, I didn't have a chance to try out Python. However, I'm intersted in opportunity to use existing Python's ecosystem (3rd party libraries) within the Nim (first, I'm curious; second, it can be usefull in the long run). What I understand so far from what I've seen is that Nim has an ability to call standard Python libraries and convert Python code to Nim (which is already great!). However, it is not abvious if there is chance to call non-standard module written in Python within Nim.. What do you think?
Another one for python2 not stated above is this one
https://github.com/marcoapintoo/nim-pythonize
You easily can move data from nim to python call your
3rd party lib python function and move the result back to nim for further processing.
You can see this in action here where a python based database driver is called.
https://github.com/qqtop/NimFirebird
https://github.com/qqtop/NimFirebird/blob/master/firebird.nim
Unfortunately does not work with python3 libs .
Here are my examples of calling Nim from Python.
Using ctypes:
https://github.com/octonion/puzzles/tree/master/blackjack/python-nim
Using cffi:
https://github.com/octonion/puzzles/tree/master/blackjack/python-nim-cffi
Weirdly, calling Nim from Python 2.7 is faster than the entire program in Nim.
# Nim
var
deck: array[0..9, int]
d, n, p : int
proc partitions(cards: var array[0..9, int], subtotal: int): int =
var total: int
result = 0
# Hit
for i in 0..9:
if (cards[i]>0):
total = subtotal+i+1
if (total < 21):
# Stand
result += 1
# Hit again
cards[i] -= 1
result += partitions(cards, total)
cards[i] += 1
elif (total==21):
# Stand; hit again is an automatic bust
result += 1
return result
for i in 0..8:
deck[i] = 4
deck[9] = 16
d = 0
for i in 0..9:
# Dealer showing
deck[i] -= 1
p = 0
for j in 0..9:
deck[j] -= 1
n = partitions(deck, j+1)
deck[j] += 1
p += n
echo "Dealer showing ", i," partitions = ",p
d += p
deck[i] += 1
echo "Total partitions = ",d