Nine Methods of Executing Functions in python

  • 2021-10-15 10:52:53
  • OfStack

Directory method 1: directly call the function to run
Method 2: Use partial functions to execute
Method 3: Dynamic execution using eval
Method 4: Use getattr to dynamically get execution
Method 5: Use the dictionary of the class itself
Method 6: Use global () to get the execution
Method 7: Compile and run from text
Method 8: Use attrgetter to get execution
Method 9: Execute with methodcaller

Method 1: Call the function directly to run

This is the simplest and most intuitive method


def task():
    print("running task")

task()

The same is true if it is in a class


class Task:
    def task(self):
        print("running task")

Task().task()

Method 2: Use partial functions to execute

In the functools built-in library, there is an partial method specifically used to generate partial functions.


def power(x, n):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
    return s

from functools import partial

power_2=partial(power, n=2)
power_2(2)  # output: 4
power_2(3)  # output: 9

Method 3: Dynamic execution using eval

If you need to execute the function dynamically, you can use eval + string to execute the function.


import sys

def pre_task():
    print("running pre_task")

def task():
    print("running task")

def post_task():
    print("running post_task")

argvs = sys.argv[1:]

for action in argvs:
    eval(action)()

The running effect is as follows


$ python demo.py pre_task task post_task
running pre_task
running task
running post_task

Method 4: Use getattr to dynamically get execution

If you put all the functions in a class and define them as static methods, you don't need to use eval, and then use getattr to get and call them.


import sys

class Task:
    @staticmethod
    def pre_task():
        print("running pre_task")

    @staticmethod
    def task():
        print("running task")

    @staticmethod
    def post_task():
        print("running post_task")

argvs = sys.argv[1:]

task = Task()

for action in argvs:
    func = getattr(task, action)
    func()

Method 5: Use the dictionary of the class itself

We all know that objects have a magic method of __dict__ (), which holds the properties and methods of all objects.

At this point, you can think about 1. If it is still the above code, can I directly take the __dict__ () of the instance get the function?

I believe many people will answer wrong.

What we defined above is a static method, which is not bound to the instance, so the static method belongs to the class, but not to the instance. Although the instance has the right (can be called), it has no ownership.

Therefore, if you want to get a function through __dict__, you have to get it through the class itself Task, and the fetched function, calling method and peacetime are not the same, so you must get it with __func__ before you can call it.


import sys

class Task:
    @staticmethod
    def pre_task():
        print("running pre_task")

func = Task.__dict__.get("pre_task")
func.__func__()

Method 6: Use global () to get the execution

The above put into the class, just to facilitate the use of getattr method, in fact, not put into the class, is also possible. At this point you need to use globals () or locals (), which is essentially a dictionary, and you can get the function directly from get.


import sys

def pre_task():
    print("running pre_task")

def task():
    print("running task")

def post_task():
    print("running post_task")

argvs = sys.argv[1:]

for action in argvs:
    globals().get(action)()

Method 7: Compile and run from text

First define a string, the content is the content of your function, such as the above pre_task, and then through the compile function into the compilation, converted into bytecode, and finally use exec to execute it.


pre_task = """
print("running pre_task")
"""
exec(compile(pre_task, '<string>', 'exec'))

If your code is placed in an txt text, although it cannot be directly imported and run, it can still be read through open, and finally compiled and run with compile function.


with open('source.txt') as f:
    source = f.read()
    exec(compile(source, 'source.txt', 'exec'))

Method 8: Use attrgetter to get execution

In operator this built-in library, there is a method to obtain attributes, called attrgetter, which can be executed after obtaining functions.


class Task:
    def task(self):
        print("running task")

Task().task()
0

Method 9: Execute using methodcaller

It is also the built-in library of operator, which has an methodcaller method. Using it, you can also call the instance method dynamically.


class Task:
    def task(self):
        print("running task")

Task().task()
1

These are the 10 methods that I summarized for function execution. Many methods are well known, but there are also several methods that are almost unknown, especially the two methods that use operator library later.

The above is the python execution function of the 9 methods of the detailed content, more about the python execution function of the method of information please pay attention to other related articles on this site!


Related articles: