Function Codes in Python

/ / How To

Edited by Eden Xu, Tatyana Frid

This is a recap of a FocusKPI Analytics at Work chat. Join our LinkedIn group to learn more.


Speaker: Xuanfu Wu

Expertise: Data analytics, statistical analysis, machine learning, data engineering with Python, SAS, SQL, R, C++, Java and UNIX.


We are mainly talking about two topics today:

1. Why use the lambda function in data manipulation?

2. What is decorator and first-order class closure and how it helps you code more flexibly and functionally?

Lambda function is also known as anonymous function. The syntax is quite easy as you just assign a variable to the function and it will return the result.

  x_square = lambda x: x**2
  x_square(5)

Output:25

The logic of Lambda is actually the same as a function. What is the difference then? Compare the two pieces of code below:

  import dis
  add = lambda x,y: x+y
  type(add)
  dis.dis(add)
  add

Output: <function __main__.<lambda>(x,y)>

  def add(x,y):
  return x+y
  type(add)
  dis.dis(add)
  add

Output: <function __main__.add(x,y)>

Basically the type is different. And remember lambda function can be more complicated, as here we are just giving a neat example. When lambda function and an ordinary function return the same output, the former typically takes fewer steps, so typically, the lambda function is more efficient.

It supports positional arguments, named (keyword) arguments, variable list of arguments(varargs), variable list of keyword arguments, etc.. However, it can only have one expression.

High order functions are those contain other functions as a parameter or returns a function as an output. However, this assignment takes the function as a reference instead of directly calling on it. Lambda function could also be one of them.

Functions can be defined within the scope of another function. If this type of function definition is used, the inner function is only in scope inside the outer function, so it is most often useful when the inner function is being returned (moving it to the outer scope) or when it is being passed into another function. This is how nested functions work.

BTW, you use inner functions to protect information happening outside the outer function, meaning that they are hidden from the global scope. You can use an inner and outer function with a high order function as well. Meanwhile, closures also assure the inner function to access the free variable(argument in outer function) even the outer function has been executed.

Decorator is similar to the high order function, but with a decorator, we can add the behavior of the function to the original function. It is usually expressed with @decorator syntax prefixing a function. So the decorator has a similar pattern and provides more functionality than the closure.


If you are interested in this topic or have any related questions about our event and service, please reach out to NEWS@FOCUSKPI.COM.