0% found this document useful (0 votes)
25 views

First Class Function

First class function in python
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

First Class Function

First class function in python
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 3

First class objects

-> can be passed to a function as an argument.


-> can be returned from a function.
-> can be assigned to a variable.
-> can be stored in a data structure (such as list, tuple, dict
etc.)
-> Types such as int, float, string, tuple, list and many more
are first-class objects.
-> Function (function) are also first class objects.

Higher Order function


-> Higher order functions are functions that
-> takes a function as an argument.
-> and/or return a function.

Docstrings and annotations


->We can document our functions (and modules, classes
etc) to achieve the same result using docstrings. PEP 257
-> If the first line function body is a string (not an
assignment, not a comment just a string by itself), it will be
interpreted as a docstring.

-> def func_a(a):


“documentation”
return a

-> Where are docstrings stored?


-> in the function’s __doc__ property.
-> Function Annotations
-> Function annotations give us an additional way to
document our functions. PEP 3107
-> def my_func(a: <expression>, b: <expression>) ->
<expression>:
pass

-> Annotation can be any expression


-> def my_func(a: str, b: ‘int > 0’) -> ‘str’:
return a*b
-> def my_func(a: str, b: [1, 2, 3]) -> ‘str’:
return a*b
-> x,y = 3,5
-> def my_func(a: str) -> ‘a repeated ’ + str(max(x,y)) +
‘times’:
return a*max(x,y)

-> default values *args, **kwargs


-> can still be used as before
-> def my_func(a: str = ‘xyz’, b: int = 1) -> str:
pass
-> def my_func(a: str = ‘xyz’,
*args: ‘additional parameters’,
b: int = 1,
**kwargs: ‘addtional keyword only params’)
-> str:
pass
Where are annotations stored?
-> In the __annotations__ property of the function.
-> it is a dictionary (keys are the parameter names, for a
return annotation, the key is return).
-> my_func.__annotations__

Where does python use docstrings and annotations?


-> it doesn’t really.
-> mainly used by external tools and modules.

-> Example: apps that generate documentation from your


code. (Sphinx).
-> Docstrings and annotations are entirely optional, and do
not “force” anything in our python code.
-> We’ll look at an enhanced version of annotations in an
upcoming on type hints.

->

You might also like