Explicitly Define Datatype in Python Function
Asked Answered
V

5

22

I want to define 2 variables in python function and define them as float explicitly. However, when i tried to define them in the function parameter, it's showing syntax error.

Please help me get the desired output.

Here is the code:

def add(float (x) , float (y)) :
    z = (x+y)
    return (print ("The required Sum is: ", z))

add (5, 8)
Vipul answered 5/4, 2017 at 14:5 Comment(2)
No, you cannot do such a thing in Python. Why would you want it?Togoland
Please see Other languages have "variables", Python has "names". If you want more details on this important topic you may find this article helpful: Facts and myths about Python names and values, which was written by SO veteran Ned Batchelder.Nordin
F
53

Python is a strongly-typed dynamic language, which associates types with values, not names. If you want to force callers to provide data of specific types the only way you can do so is by adding explicit checks inside your function.

Fairly recently type annotations were added to the language. and now you can write syntactically correct function specifications including the types of arguments and return values. The annotated version for your example would be

def add(x: float, y: float) -> float:
    return x+y

Note, though, that this is syntax only. Nothing in the Python interpreter actions any of this. There are external tools like mypy that can help you to achieve your goal, which are now maturing fast to become an established part of the language (though one hopes they will remain strictly optional, bearing in mind the vast corpus of type-free code that exists).

Annotations are finding a wider use than originally intended in tools like pydantic, which uses them to perform data validation. This supports interesting new paradigms, exploited by (for example) the FastAPI server, demonstrating great potential to improve web coding productivity.

Fanechka answered 5/4, 2017 at 14:40 Comment(0)
G
8

you can check however the instance that is provided in the function if its the type you want!

def add(x: float, y: float) -> float:
      if not isinstance(x, float):
           raise TypeError("x and y variables not of type float")

similarly for the y var!

Gca answered 4/6, 2021 at 12:52 Comment(2)
Do format the code and add the information for better understanding.Corruption
You could indeed perform those check, at the cost of increased volume and complexity of code. The pythonic way is to assume the happy path (all types correct) is being followed, and cross the bridge of handling any errors when they become obvious (i.e. when the code raises an exception). To do otherwise ignores the nature of the language, but if you must do it then at least use annotation-driven tools like pydantic, not hand-crafted code.Fanechka
L
1

It is not possible to define Data-Type in Python as it is strongly typed dynamic language , but it is possible to add Type-Hint .

link: str

This is a sample of type-hint in python. You can also check-out.

Also take a look at mypy:

Lox answered 5/2, 2019 at 1:32 Comment(0)
C
0

Change the function z = float(x+y) to z = float(x)+ float(y)

At this point we assume we are just adding numbers together.

Let's make sure we're always working with floats. Convert your arguments to floats before you add them together. You can do this with the float() function.

Ok let's make sure no matter what comes in it's converted to a float

    def add(x, y):
        z = float(x)+ float(y)
        print "The required Sum is:  {}".format(z)
        return z

    add (5, 8)

But what if a & b are strings ?? Need to take care of that.

def add(x, y)
    try:
        a = float(x)  
        b = float(y)
    except ValueError:
        return None
     else:
        return True

By the way, No need to check the datatype in python, making it much simpler

def addSum(x,y):
    return x+y

addSum(2.2, 5.6)
7.8
addSum(float(2), float(5))
7.0
addSum(2, 5)
7
addSum("Hello ", "World!!")
'Hello World'
Caterwaul answered 5/4, 2017 at 14:6 Comment(0)
P
0

I would use assert isinstance

#!/usr/bin/env python3

import sys

def this_add(x: float, y: float):
    assert isinstance(x, float), f"[e] {x} should be a float and it is {type(x)}"
    assert isinstance(y, float), f"[e] {y} should be a float and it is {type(y)}"
    z = (x+y)
    return z

print(f"The required Sum is: {this_add(5.2, 8.9)}")

import unittest

class TestStringMethods(unittest.TestCase):
    def test_int(self):
        self.assertRaises(AssertionError, this_add, 5, 8)
    def test_float(self):
        self.assertEqual(14.0, this_add(5.1, 8.9) )
    def test_float_and_int(self):
        self.assertRaises(AssertionError, this_add, 5.1, 8)
    def test_int_and_float(self):
        self.assertRaises(AssertionError, this_add, 5, 8.9)
    def test_tuple(self):
        self.assertRaises(AssertionError, this_add, (5.1, 8.9), 0)
    def test_string(self):
        self.assertRaises(AssertionError, this_add, "5.1", "8.9")
unittest.main()
Palladous answered 4/6, 2023 at 19:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.