Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control parameters accuracy of a function in Python

I have this function in Python:

def Rotate_Vector(vector, axis, direction):

where vector is a tuple of 3 elements (each element represent the three coordinates x,y,z of the vector on Cartesian axes), axis are the coordinates of an axis, and direction is an integer representing the clockwise or counter-clockwise movement.

I want to control, in my funcion, if the input parameters are correctly:

  • vector must be a tuple of 3 integer
  • axis must be a tuple of 3 integer, and the possibile value should be -1, 0, 1
  • direction must be an integer with value +1 or -1.

I would like to know the right way to do these controls (types, values and numbers of elements) in a function.

Edit:

axis could be 6 possibile cases: (1,0,0) (-1,0,0) (0,1,0) (0,-1,0) (0,0,1) (0,0,-1)

like image 468
Kyrol Avatar asked Sep 05 '26 13:09

Kyrol


1 Answers

The short answer is: don't. Python is duck typed, so just do what you need to, and if it doesn't work, then it'll go wrong.

For example, if you limit vector to a length 3 tuple, then what about the person who passes in a list? If it does the same job, why does it matter to you what they pass in?

If you really feel you need to, then do something like this:

if direction not in {1, -1}:
    raise ValueError("direction must be +1 or -1")

if not len(vector) == 3:
    raise ValueError("vector must contain 3 values")

etc...

However, this violates Python's principle of ask for forgiveness, not permission.

I would also note a better option here is to avoid using magic numbers. Add, for instance, Vector.FORWARD = +1 and Vector.BACKWARD = -1 and then tell people to pass those into direction. This still gives flexibility, but gives people guidance as to what to use for direction. Again, you could provide namedtuples for vectors to provide guidance when constructing them.

It's also worth noting that PEP-8 advises lowercase_with_underscores for function names, so Rotate_Vector() isn't a particularly good function name unless you are forced by existing convention in a project.

like image 158
Gareth Latty Avatar answered Sep 08 '26 03:09

Gareth Latty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!