Teachnique
      CourseRoadmaps
      Login

      OverviewCommentsUser InputNumbersBooleansHistoryHello World ProgramEnvironment SetupSyntaxVariablesData TypesType CastingUnicode SystemLiteralsOperators

      Control FlowBreak StatementContinue StatementPass StatementNested LoopsDecision MakingIf StatementIf-else StatementNested IF StatementMatch-Case StatementLoopsFor LoopsFor-else LoopsWhile Loops

      FunctionsBuilt-in FunctionsDefault ArgumentsKeyword ArgumentsKeyword-Only ArgumentsPositional ArgumentsPositional-Only ArgumentsArbitrary ArgumentsVariable ScopeFunction AnnotationsModules

      StringSlicing StringsModify StringsString ConcatenationString FormattingEscape CharactersString MethodsString Exercises

      ListsList ExercisesAccess List ItemsChange List ItemsAdd List ItemsRemove List ItemsLoop ListsList ComprehensionSort ListsCopy ListsJoin ListsList Methods

      TuplesAccess Tuple ItemsUpdate TuplesUnpack Tuple ItemsLoop TuplesJoin TuplesTuple MethodsTuple Exercises

      SetsAccess Set ItemsAdd Set ItemsRemove Set ItemsLoop SetsJoin SetsCopy SetsSet OperatorsSet MethodsSet Exercises

      DictionariesDictionary ExercisesAccess Dictionary ItemsChange Dictionary ItemsAdd Dictionary ItemsRemove Dictionary ItemsDictionary View ObjectsLoop DictionariesCopy DictionariesNested DictionariesDictionary Methods

      ArraysAccess Array ItemsAdd Array ItemsRemove Array ItemsLoop ArraysCopy ArraysReverse ArraysSort ArraysJoin ArraysArray MethodsArray Exercises

      File HandlingWrite to FileRead FilesRenaming and Deleting FilesDirectoriesFile Methods

      OOP ConceptsDynamic BindingDynamic TypingAbstractionObject and ClassesEncapsulationInterfacesPackagesInner ClassesAnonymous Class and ObjectsSingleton ClassWrapper ClassesEnumsReflectionClass AttributesClass MethodsStatic MethodsConstructorsAccess ModifiersInheritancePolymorphismMethod OverridingMethod Overloading

      Feedback

      Submit request if you have any questions.

      Course
      Function Annotations

      Python Tutorial

      This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.

      Function Annotations

      The function annotation feature of Python enables you to add additional explanatory metada about the arguments declared in a function definition, and also the return data type.
      Although you can use the docstring feature of Python for documentation of a function, it may be obsolete if certain changes in the function's prototype are made. Hence, the annotation feature was introduced in Python as a result of PEP 3107.
      The annotations are not considered by Python interpreter while executing the function. They are mainly for the Python IDEs for providing a detailed documentation to the programmer.
      Annotations are any valid Python expressions added to the arguments or return data type. Simplest example of annotation is to prescribe the data type of the arguments. Annotation is mentioned as an expression after putting a colon in front of the argument.
      def myfunction(a: int, b: int):
      c = a+b
      return c
      Remember that Python is a dynamically typed language, and doesn't enforce any type checking at runtime. Hence annotating the arguments with data types doesn't have any effect while calling the function. Even if non-integer arguments are given, Python doesn't detect any error.
      def myfunction(a: int, b: int):
      c = a+b
      return c
      print (myfunction(10,20))
      print (myfunction("Hello ", "Python"))
      It will produce the following output 
      30
      Hello Python
      Annotations are ignored at runtime, but are helpful for the IDEs and static type checker libraries such as mypy.
      You can give annotation for the return data type as well. After the parentheses and before the colon symbol, put an arrow (->) followed by the annotation. For example −
      def myfunction(a: int, b: int) -> int:
      c = a+b
      return c
      As using the data type as annotation is ignored at runtime, you can put any expression which acts as the metadata for the arguments. Hence, function may have any arbitrary expression as annotation as in following example
      def total(x : 'marks in Physics', y: 'marks in chemistry'):
      return x+y
      If you want to specify a default argument along with the annotation, you need to put it after the annotation expression. Default arguments must come after the required arguments in the argument list.
      def myfunction(a: "physics", b:"Maths" = 20) -> int:
      c = a+b
      return c
      print (myfunction(10))
      The function in Python is also an object, and one of its attributes is __annotations__. You can check with dir() function.
      print (dir(myfunction))
      This will print the list of myfunction object containing __annotations__ as one of the attributes.
      ['__annotations__', '__builtins__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__getstate__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
      The __annotations__ attribute itself is a dictionary in which arguments are keys and anootations their values.
      def myfunction(a: "physics", b:"Maths" = 20) -> int:
      c = a+b
      return c
      print (myfunction.__annotations__)
      It will produce the following output
      {'a': 'physics', 'b': 'Maths', 'return': <class 'int'>}
      You may have arbitrary positional and/or arbitrary keyword arguments for a function. Annotations can be given for them also.
      def myfunction(*args: "arbitrary args", **kwargs: "arbitrary keyword args") -> int:
      pass
      print (myfunction.__annotations__)
      It will produce the following output
      {'args': 'arbitrary args', 'kwargs': 'arbitrary keyword args', 'return': <class 'int'>}
      In case you need to provide more than one annotation expressions to a function argument, give it in the form of a dictionary object in front of the argument itself.
      def division(num: dict(type=float, msg='numerator'), den: dict(type=float, msg='denominator')) -> float:
      return num/den
      print (division.__annotations__)
      
      It will produce the following output
      {'num': {'type': <class 'float'>, 'msg': 'numerator'}, 'den': {'type': <class 'float'>, 'msg': 'denominator'}, 'return': <class 'float'>}

      Practice with Online Editor

      Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
      Remember to save code(Ctrl + S Or Command + S) before run it.