Question on the python language. A class method takes an object by parameter.
def intersection(self, vp):
Is it possible to assign a type to the vp parameter in the code?
Question on the python language. A class method takes an object by parameter.
def intersection(self, vp):
Is it possible to assign a type to the vp parameter in the code?
If we are talking about static typing, then no, it is impossible. The maximum that is possible is contracts that are checked at run time when the function is called. The simplest is using assert
. For example, something like this:
def intersection(self, vp): assert type(vp) is tuple and \ all(type(x) in (int, long) for x in vp), \ "vp must be a tuple of integers" ...
If you want syntactic sugar, Python 3 has annotations that you can use.
@typecheck def intersection(self, vp: tuple_of(int)): ...
And then check the types of the decorator, for example, http://code.activestate.com/recipes/572161/ . In Python 2.x there are no annotations, the maximum that can be done is a decorator in the spirit of :
@requires("vp", tuple) def intersection(self, vp): ...
Or register the contract in docstring'e , in the spirit of:
def intersection(self, vp): """ Does something. inv: type(vp) is tuple """ ...
If something else was meant, please clarify the question, explaining what it means to “assign the type.”
Source: https://ru.stackoverflow.com/questions/110384/
All Articles