I want to force that arg to function will be str , so I used :str
into function args
def func (a:str):
print(a)
func(int(2))
This code is work and didn't fail , why?
I want to force that arg to function will be str , so I used :str
into function args
def func (a:str):
print(a)
func(int(2))
This code is work and didn't fail , why?
def func (a:str):
print(a)
func(int(2))
What you have used is Type Hint as described PEP 484. Shortly speaking it is only guideline and do not have any enforcing effect. You might use isinstance
function for checking if argument conforms to your requirement and raise
TypeError
otherwise following way:
def func(a):
if not isinstance(a, str):
raise TypeError
print(a)
You can also (alongside the runtime check or instead of it) use a static type checker which will attempt to leverage those annotations (and possibly what it can infer from the un-annotated code) and check that they all match. By default Python (wilfully and knowingly) includes syntax to add type hints, but will not perform any type checking: that's not considered part of the python language itself (although there are parts of python which use the type annotations, like dataclasses).
The premier type-checker is mypy and developed under the umbrella of the Python project, but there are various alternatives (I've not necessarily tested so YMMV) e.g. Facebook's pyre, google's pytype or microsoft's pyright, as well as integrated tools such as the built-in type-checking of IDEs like jetbrains'.