Skip to content

Commit

Permalink
Add unary operators support
Browse files Browse the repository at this point in the history
  • Loading branch information
mrkn committed Jan 8, 2023
1 parent edc6a2f commit c5ba6e0
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/pycall/pyobject_wrapper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ def self.extend_object(obj)
end

OPERATOR_METHOD_NAMES = {
# Unary operators
:+@ => :__pos__,
:-@ => :__neg__,
:~ => :__invert__,

# Binary operators
:+ => :__add__,
:- => :__sub__,
:* => :__mul__,
Expand Down
20 changes: 20 additions & 0 deletions test/pycall/test-operators.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class PyCallOperatorsTest < Test::Unit::TestCase
def setup
@simple_class = PyCall.import_module("pycall.simple_class").SimpleClass
end

def test_unary_positive
x = @simple_class.new("x")
assert_equal "+x", +x
end

def test_unary_negative
x = @simple_class.new("x")
assert_equal "-x", -x
end

def test_unary_invert
x = @simple_class.new("x")
assert_equal "~x", ~x
end
end
9 changes: 9 additions & 0 deletions test/python/pycall/simple_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,14 @@ def initialize(self, x):
self.x = x
return 'initialized'

def __neg__(self):
return "-{}".format(self.x)

def __pos__(self):
return "+{}".format(self.x)

def __invert__(self):
return "~{}".format(self.x)

class SimpleSubClass(SimpleClass):
pass

0 comments on commit c5ba6e0

Please sign in to comment.