ImranAli
ImranAli

Reputation: 176

Python - Specify arguments' data type

To keep things simplistic, consider the Python function:

def to_string(value):
    return str(value)

Since we cannot define data types of parameters in Python (as for as I know), when I pass 1/2 to above function, it automatically converts 1/2 to 0.5 and then returns string '0.5'. How do I make it return '1/2'? How do I force Python to treat arguments to be of certain data type, no matter how they "appear"?

Upvotes: 0

Views: 664

Answers (1)

Helios
Helios

Reputation: 715

Here (in python 3) 1/2 is evaluated to 0.5 before being even passed into the function. For this specific example you have lost the information, due to possible float accuracy errors, before the function is even called; In theory you can get back to 1/2 from 0.5 but you should not rely on this float manipulation. In order to not lose this accuracy here you should probably treat a fraction as two pieces of integer information as it really is, instead of one float.

from fractions import gcd

def to_string(n, d):
    g = gcd(n, d)
    return str(n//g) + "/" + str(d//g)

If what you are asking is specifically about fractions then a class built around this idea is probably your best bet. If your example is not explanatory then (famously) python does not have type enforcement. However you can read here https://docs.python.org/3/library/typing.html about modernisation of this idea and decorators.

Upvotes: 1

Related Questions