Reputation: 47
def adding(a, b) -> int:
return a+b
print(adding(1,0.7))
Like in this code...I get output 1.7 instead of expected 1..so it basically means there is no "type conversion"?
Upvotes: 0
Views: 115
Reputation: 1449
Yes you are correct, more information in https://docs.python.org/3/library/typing.html. Also, for detecting types you can use function type/1
and rewrite example as:
>>> def adding(a: int, b: int) -> int:
... if(type(a) is int and type(b) is int):
... return a + b
... else:
... print("Bad Arguments: Expected Integers")
...
>>> adding(1, 0.7)
Bad Arguments: Expected Integers
>>> adding(1, 7)
8
The annotation of type ->
provided info about - what type the current function should return. The annotation of type :
provided info about - what types of arguments is expected in current function. Hope, this will be helpful
Upvotes: 0
Reputation: 66449
That's correct, it's more for documentation than anything else.
Erlang (with which I'm more familiar) has the same concept, but they call it type specification. Dynamic languages sometimes have a way to suggest all the possible types a parameter might be, which helps future programmers. Sometimes there's a tool too (Erlang calls it dialyzer), which can be run against the codebase to ensure the value being passed to a function is one of the types that you "hinted" it might be.
It looks like there's a similar tool for Python called mypy that will use your "type hints" to perform some static type checking.
Mypy is an optional static type checker for Python that aims to combine the benefits of dynamic (or "duck") typing and static typing. Mypy combines the expressive power and convenience of Python with a powerful type system and compile-time type checking. Mypy type checks standard Python programs; run them using any Python VM with basically no runtime overhead.
Upvotes: 1