Functions are a common usage of first-class objects (citizens)

Posted May 26, 20201 min read

What is a first-class function

> First-class objects are defined as program entities that meet the following conditions:
>
>-Create at runtime
>-Can assign values   to elements in variables or data structures
>-Can be passed as a parameter to the function
>-Can be used as the return result of the function

So in python, function, int, str, etc. are all first-class citizens


Common applications of first-class functions

  • Check if the function is callable

  • View the attributes of the function(function introspection)


  1. Function callable object callable() function

    If you want to judge whether the function can be called, you can use the built-in callable() function

     def foo():
         return 'Hello'
     bool_result = callable(foo)

    Run the code, the value of bool_result is True

  2. Function introspection

    Use the dir function to discover the attributes of the function

     dir(foo)

    The properties of the run output foo are as follows:

     ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', ' __ge__ ',' __get__ ',' __getattribute__ ',' __globals__ ',' __gt__ ',' __hash__ ',' __init__ ',' __init_subclass__ ',' __kwdefaults__ ',' __le__ ',' __lt__ ',' __module__ ',' __name__ ' , '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']