Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does python recognize the type of argument?

I'd like to define a function that returns the minimum element of a list. So I'd defined a 'minOfList' function as below:

def minOfList(a_list):
n = len(a_list)
x = a_list[0]
for i in range(n):
    if a_list[i] <= x:
        x = a_list[i]
    else:
        x = x
return x

First I set a list and put that into the above function.

x = [1, 1, 5, 6, 9, 5, 4, 5]
minOfList(x)

Then I redefined x as a tuple and feed x into the function.

x = (1, 1, 5, 6, 9, 5, 4, 5)
minOfList(x)

Whether I define x as a list or a tuple, the function worked well.

Question: How does python know exactly which data type of the argument is fed into the function? Additionally, I'd like know a way to designate data type of the argument when I define a function?

like image 693
Tae Choi Avatar asked Dec 17 '25 13:12

Tae Choi


1 Answers

Python doesn't use static type-casting. So the short answer is No, Python doesn't know what type of variable is being passed into your function.

There is a way to check manually however, using the isinstance() function.

isinstance(your_var, type); returns True or False.

Here is an example that relates to the function you are building.

if isinstance(a_list, list) or isinstance(a_list, tuple):
     Your code
else:
     Return bad var type

In addition, there is a way to recommend to the user the type of the variable the function expects to take, using this syntax:

def minOfList(a_list: list):
     return

This lets the user know what type they should be passing in. Be cautioned however, this does not force the parameter type - the use can still pass in any variable.

Hope this helps!

like image 156
Conrad Selig Avatar answered Dec 20 '25 11:12

Conrad Selig



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!