Skip to content

Commit 11022d3

Browse files
committed
try to make code more efficient
1 parent 1e04cc1 commit 11022d3

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

quantlib/instruments/_swap.pxd

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,4 @@ cdef extern from 'ql/instruments/swap.hpp' namespace 'QuantLib' nogil:
3636
DiscountFactor endDiscounts(Size j) except +
3737
DiscountFactor npvDateDiscount() except +
3838
Leg& leg(Size j) except +
39+
const vector[Leg]& legs()

quantlib/instruments/swap.pyx

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,11 @@ from quantlib.types cimport Size
1111
from quantlib.cashflow cimport Leg
1212
cimport quantlib.time._date as _date
1313
from quantlib.time.date cimport date_from_qldate
14+
from quantlib._cashflow cimport Leg as QlLeg
15+
1416
from . cimport _swap
1517

16-
cdef inline _swap.Swap* get_swap(Swap swap):
18+
cdef inline _swap.Swap* get_swap(Swap swap) noexcept:
1719
""" Utility function to extract a properly casted Swap pointer out of the
1820
internal _thisptr attribute of the Instrument base class. """
1921

@@ -60,10 +62,18 @@ cdef class Swap(Instrument):
6062

6163
def leg(self, int i):
6264
cdef Leg leg = Leg.__new__(Leg)
63-
leg._thisptr = get_swap(self).leg(i)
65+
cdef _swap.Swap* swap = <_swap.Swap*>self._thisptr.get()
66+
if 0 <= i < swap.numberOfLegs():
67+
leg._thisptr = swap.legs()[i]
68+
else:
69+
raise IndexError(f"leg #{i} doesn't exist")
6470
return leg
6571

6672
def __getitem__(self, int i):
6773
cdef Leg leg = Leg.__new__(Leg)
68-
leg._thisptr = get_swap(self).leg(i)
74+
cdef _swap.Swap* swap = <_swap.Swap*>self._thisptr.get()
75+
if 0 <= i < swap.numberOfLegs():
76+
leg._thisptr = swap.legs()[i]
77+
else:
78+
raise IndexError(f"leg #{i} doesn't exist")
6979
return leg

0 commit comments

Comments
 (0)