Python Forum
determine parameter type in definition function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
determine parameter type in definition function
#1
hi
in address https://realpython.com/if-name-main-python/#
In the definition of the echo function, the type of parameters was written. namely:
def echo(text: str, repetitions: int = 3) -> str:
is this true? is it better to written or not? what is the meaning of -> srt?
thanks
Reply
#2
Those are annotations. They tell the programmer what argument types are expected and what type is returned by the function. There are also static analysis tools that use the annotation information to identify potential bugs in you Python code.

The annotations do not affect the execution of a Python program. echo(123) is a valid Python statement that will run up to the point where some operation is performed on "text" that is not valid for an int.
Error:
>>> echo(123) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\djhys\Documents\python\musings\echo.py", line 5, in echo echoed_text += f"{text[-i:]}\n" ~~~~^^^^^ TypeError: 'int' object is not subscriptable
A static analysis tool, like mypy, can spot this error before the code is executed.

file test.py
from echo import echo

echo(123)
Runing mypy from cmd shell.
Output:
(env) > mypy junk.py test.py:3: error: Argument 1 to "echo" has incompatible type "int"; expected "str" [arg-type] Found 1 error in 1 file (checked 1 source file)
"-> str" tells Python that the function returns a str object.

More about annotations:

https://www.geeksforgeeks.org/function-a...ns-python/
akbarza likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  class definition and problem with a method HerrAyas 2 268 Apr-01-2024, 03:34 PM
Last Post: HerrAyas
  mutable argument in function definition akbarza 1 492 Dec-15-2023, 02:00 PM
Last Post: deanhystad
  How does sqlite3 module determine value type mirlos 2 955 Dec-12-2023, 09:37 AM
Last Post: mirlos
  error occuring in definition a class akbarza 3 721 Nov-26-2023, 09:28 AM
Last Post: Yoriz
  Function parameter not writing to variable Karp 5 954 Aug-07-2023, 05:58 PM
Last Post: Karp
  [split] Explain the python code in this definition Led_Zeppelin 1 749 Jan-13-2023, 10:20 PM
Last Post: deanhystad
  [ERROR] ParamValidationError: Parameter validation failed: Invalid type for parameter gdbengo 3 11,099 Dec-26-2022, 08:48 AM
Last Post: ibreeden
  i want to use type= as a function/method keyword argument Skaperen 9 1,896 Nov-06-2022, 04:28 AM
Last Post: Skaperen
  Explain the python code in this definition Led_Zeppelin 1 1,106 Oct-27-2022, 04:04 AM
Last Post: deanhystad
  meaning of -> syntax in function definition DrakeSoft 5 1,977 Apr-09-2022, 07:45 AM
Last Post: DrakeSoft

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020