Thought leadership from the most innovative tech companies, all in one place.

9 Ways to Call a Function in Python

How to call a function in Python?

image

1. Directly Function Call

This is the simplest and most intuitive way:

def test():
    print("This is a test")
test()

2. Use partial() Function

In the built-in library of functools, there is a partial method dedicated to generating 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(3)  # output: 9
power_2(4)  # output: 16

3. Use eval()

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

# demo.pyimport 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)()

To execute:

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

4. Use getattr()

If you put all the functions in the class and define them as static methods, you can 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()

5. Use dict()

We all know that the object has a __dict__()magic method, it stores the properties and methods of any object. For example:

image

You can call class method use __dict__.get :

import sys

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

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

# Output
$ python /tmp/demo.py
running pre_task

6. Use global()

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)()

# Output
$ python /tmp/demo.py pre_task task post_task
running pre_task
running task
running post_task

7. Compile and Run From Text

You can define your function in a string, and use the compile function to compile it into byte code, and then used exec to execute it.

pre_task = """
print("running pre_task")
"""
exec(compile(pre_task, '', 'exec'))# Or from a text file
with open('source.txt') as f:
    source = f.read()
    exec(compile(source, 'source.txt', 'exec'))

8. Use attrgetter()

In the built-in library of operator, there is a method for obtaining attributes, called attrgetter, execute after obtaining the function.

from operator import attrgetter

class People:
    def speak(self, dest):
        print("Hello, %s" %dest)

p = People()
caller = attrgetter("speak")
caller(p)("Tony")

# Output
$ python /tmp/demo.py
Hello, Tony

9. Use methodcaller()

There is also a methodcaller method in operator :

from operator import methodcaller

class People:
    def speak(self, dest):
        print("Hello, %s" %dest)

caller = methodcaller("speak", "Tony")
p = People()
caller(p)

# Output
$ python /tmp/demo.py
Hello, Tony

And these are the nine ways in which a function can be called in Python.

Thank you for reading.




Continue Learning