PyBind
PyBind.rb is a lightweight Ruby - Python binding using ffi
, it aims to create a way to call exsisting Python functions in Ruby. With the power of PyBind.rb, you can use all data-science packages in Python, e.g.: numpy
, pandas
, matplotlib
, and even tensorflow
.
More use-cases can be found in examples
folder.
Installation
Add this line to your application's Gemfile:
gem 'pybind'
And then execute:
$ bundle
Or install it yourself as:
$ gem install pybind
Usage
Hello world with PyBind.rb
require 'pybind'
PyBind.eval('print("Hello, world!")')
PyBind.execfile('examples/hello_world.py')
PyBind.builtin.print.('hello, world!')
Import Python modules
require 'pybind'
os = PyBind.import('os')
puts os.name
require 'pybind'
include PyBind::Import
pyimport 'os'
puts os.name
Customize convertor between Ruby & Python object
require 'pybind'
Fraction = PyBind.import('fractions').Fraction
class PyFraction
include PyBind::PyObjectWrapper
pybind_type Fraction
end
f = Fraction.(1, 2)
f.kind_of? PyFraction
f.numerator
f.denominator
Or you can map Python object to exsisting Ruby class
require 'pybind'
class Rational
include PyBind::PyObjectWrapper
Fraction = PyBind.import('fractions').Fraction
pybind_type Fraction do |pystruct|
pyobj = pystruct.to_ruby_object
new(pyobj.numerator, pyobj.denominator)
end
def to_python
Fraction.(self.numerator, self.denominator)
end
end
If you don't like the dot everywhere before the function call (just like me), you can just require 'pybind/autocall'
.
Note that this will heavily change the behavior of your code, but the life will be easier.
require 'pybind'
require 'pybind/autocall'
PyBind.builtin.print('Hello, world!')
Development
After checking out the repo, run bin/setup
to install dependencies. You can also run bin/console
for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install
. To release a new version, update the version number in version.rb
, and then run bundle exec rake release
, which will create a git tag for the version, push git commits and tags, and push the .gem
file to rubygems.org.
Contributing
PyBind.rb originally forked from pycall
, special thanks goes to Kenta Murata (mrkn
) for his brilliant idea.
Bug reports and pull requests are welcome on GitHub at https://github.com/bbtfr/pybind.rb This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.