Reputation: 329
To make my Cython code more faster, I like to declare variable types as much as possible.
cpdef void __init__(self, config, protocol=None, int slave_number, int fifo_length=170, float speed_factor=1.0) except *:
assert 0 < config.watermark_height <= fifo_length
assert protocol is None
assert slave_number is int
self.config = config
self.protocol = protocol
self.slave_number = slave_number
self.speed_factor = speed_factor
2 questions:
How do I declare the self.slave_number variable as int?#
Is the assertion (e.g. slave_numbers is int) unnecessary if I cp-function parameter already says its an int?
Thank you!
Upvotes: 0
Views: 39
Reputation: 7293
The variables from the Extension type are defined in the class declaration. In your situation:
cdef class SpeedClass:
cdef int slave_number
cdef ...
A call to __init__
will cast the argument to an integer and error when the operation is impossible. You can thus pass a floating point value to the function. From inside the function, slave_numbers
is always an integer as it will have been casted at call-time anyway and the check is useless. I couldn't find this information explicitly in the docs so I have tested it with a small example (see below).
def f1(int i):
print(type(i))
return i*2
that you can test from the command line as
python3 -c 'import test_arguments; print(test_arguments.f1(1))'
or
python3 -c 'import test_arguments; print(test_arguments.f1(1.23))'
Upvotes: 2