user11869
user11869

Reputation: 1129

python: check function parameter types

Since I just switched to Python from C++, I feel like python does not care much about type safety. For example, can anyone explain to me why checking the types of function parameters is not necessary in Python?

Say I defined a Vector class as follows:

class Vector:
      def __init__(self, *args):
          # args contains the components of a vector
          # shouldn't I check if all the elements contained in args are all numbers??

And now I want to do dot product between two vectors, so I add another function:

def dot(self,other):
     # shouldn't I check the two vectors have the same dimension first??
     ....

Upvotes: 0

Views: 1653

Answers (2)

Juan Rey Hernández
Juan Rey Hernández

Reputation: 2858

It is true that in python there is no need to check the types of the parameters of a function, but maybe you wanted an effect like this...

These raise Exception occur at runtime...

class Vector:

    def __init__(self, *args):    

        #if all the elements contained in args are all numbers
        wrong_indexes = []
        for i, component in enumerate(args):
            if not isinstance(component, int):
                wrong_indexes += [i]

        if wrong_indexes:
            error = '\nCheck Types:'
            for index in wrong_indexes:
                error += ("\nThe component %d not is int type." % (index+1))
            raise Exception(error)

        self.components = args

        #......


    def dot(self, other):
        #the two vectors have the same dimension??
        if len(other.components) != len(self.components):
            raise Exception("The vectors dont have the same dimension.")

        #.......

Upvotes: 1

SingleNegationElimination
SingleNegationElimination

Reputation: 156148

Well, as for necessity of checking the types, that may be a topic that's a bit open, but in python, its considered good form to follow "duck typing". The function just uses the interfaces it needs, and it's up to the caller to pass (or not) arguments that properly implement that interface. Depending on just how clever the function is, it may specify just how it uses the interfaces of the arguments it takes.

Upvotes: 4

Related Questions