Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I ensure parameter is correct type in Python?

Tags:

python

I'm new to Python, and am trying to figure out if there is a way to specify the variable type in a parameter definition. For example:

def function(int(integer))

as opposed to:

def function(integer)
    int(integer)

I know it's not a major difference, but I'm trying to use good programming practices here, and if I'm defining a function with a large number of parameters, it could get messy.

like image 842
umbrahunter Avatar asked Sep 20 '15 21:09

umbrahunter


People also ask

How do you specify parameter data type in Python?

Python is a strongly-typed dynamic language in which we don't have to specify the data type of the function return value and function argument. It relates type with values instead of names. The only way to specify data of specific types is by providing explicit datatypes while calling the functions.

How do you determine the type of a variable in Python?

To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.

How do you check parameters in Python?

Practical Data Science using Python To extract the number and names of the arguments from a function or function[something] to return ("arg1", "arg2"), we use the inspect module. The given code is written as follows using inspect module to find the parameters inside the functions a Method and foo.

How do you check the type of an object in Python?

The type() function is used to get the type of an object. When a single argument is passed to the type() function, it returns the type of the object. Its value is the same as the object. __class__ instance variable.


1 Answers

As of Python 3.4 you can add type annotations to a function or method:

def function(a: int):
    pass

However these types are not enforced - you can still call the function with a value that is not an integer.

Furthermore, Python is based on the idea of duck typing so you may sometimes want to accept a variety of types, such as both int and float for a particular function.

like image 70
Simeon Visser Avatar answered Sep 28 '22 19:09

Simeon Visser