Skip to content

Commit 6a2ba40

Browse files
committed
Support binary operators
1 parent 0ce329b commit 6a2ba40

File tree

2 files changed

+68
-5
lines changed

2 files changed

+68
-5
lines changed

lib/pycall/pyobject_wrapper.rb

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,24 @@ def self.extend_object(obj)
1313
end
1414

1515
OPERATOR_METHOD_NAMES = {
16-
:+ => :__add__,
17-
:- => :__sub__,
18-
:* => :__mul__,
19-
:/ => :__truediv__
16+
:+ => :__add__,
17+
:- => :__sub__,
18+
:* => :__mul__,
19+
:/ => :__truediv__,
20+
:% => :__mod__,
21+
:** => :__pow__,
22+
:<< => :__lshift__,
23+
:>> => :__rshift__,
24+
:& => :__and__,
25+
:^ => :__xor__,
26+
:| => :__or__
2027
}.freeze
2128

2229
def method_missing(name, *args)
2330
name_str = name.to_s if name.kind_of?(Symbol)
2431
name_str.chop! if name_str.end_with?('=')
2532
case name
26-
when :+, :-, :*, :/
33+
when *OPERATOR_METHOD_NAMES.keys
2734
op_name = OPERATOR_METHOD_NAMES[name]
2835
if LibPython::Helpers.hasattr?(__pyptr__, op_name)
2936
LibPython::Helpers.define_wrapper_method(self, op_name)
@@ -103,6 +110,34 @@ def *(other)
103110
def /(other)
104111
other.__rtruediv__(self.obj)
105112
end
113+
114+
def %(other)
115+
other.__rmod__(self.obj)
116+
end
117+
118+
def **(other)
119+
other.__rpow__(self.obj)
120+
end
121+
122+
def <<(other)
123+
other.__rlshift__(self.obj)
124+
end
125+
126+
def >>(other)
127+
other.__rrshift__(self.obj)
128+
end
129+
130+
def &(other)
131+
other.__rand__(self.obj)
132+
end
133+
134+
def ^(other)
135+
other.__rxor__(self.obj)
136+
end
137+
138+
def |(other)
139+
other.__ror__(self.obj)
140+
end
106141
end
107142

108143
def coerce(other)

spec/pycall/pyobject_wrapper_spec.rb

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,34 @@ module PyCall
8888
context 'when the name is :/' do
8989
it 'delegates to :__truediv__'
9090
end
91+
92+
context 'when the name is :%' do
93+
it 'delegates to :__mod__'
94+
end
95+
96+
context 'when the name is :**' do
97+
it 'delegates to :__pow__'
98+
end
99+
100+
context 'when the name is :<<' do
101+
it 'delegates to :__lshift__'
102+
end
103+
104+
context 'when the name is :>>' do
105+
it 'delegates to :__rshift__'
106+
end
107+
108+
context 'when the name is :&' do
109+
it 'delegates to :__and__'
110+
end
111+
112+
context 'when the name is :^' do
113+
it 'delegates to :__xor__'
114+
end
115+
116+
context 'when the name is :|' do
117+
it 'delegates to :__or__'
118+
end
91119
end
92120

93121
describe '#==' do

0 commit comments

Comments
 (0)