Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically calling functions - Python

Tags:

python

I have a list of functions... e.g.

def filter_bunnies(pets): ...

def filter_turtles(pets): ...

def filter_narwhals(pets): ...

Is there a way to call these functions by using a string representing their name?

e.g.

'filter_bunnies', 'filter_turtles', 'filter_narwhals'
like image 843
RadiantHex Avatar asked May 12 '10 11:05

RadiantHex


People also ask

How do you call a function automatically in Python?

Add self. initialize() to myfunc() , this should do what you are looking for. class MyClass(object): def __init__(self): pass def initialize(self): print("I'm doing some initialization") def myfunc(self): self. initialize() print("This is myfunc()!")

What are dynamic functions in Python?

Python's built-in exec() executes the Python code you pass as a string or executable object argument. This is called dynamic execution because, in contrast to normal static Python code, you can generate code and execute it at runtime. This way, you can run programmatically-created Python code.

What is dynamic function call?

Dynamic function calls are useful when you want to alter program flow according to changing circumstances. We might want our script to behave differently according to a parameter set in a URL's query string, for example. We can extract the value of this parameter and use it to call one of a number of functions.

How do you pass a dynamic value to a function in Python?

Passing arguments to the dynamic function is straight forward. We simply can make solve_for() accept *args and **kwargs then pass that to func() . Of course, you will need to handle the arguments in the function that will be called.


2 Answers

Are your function a part of an object? If so you could use getattr function:

>> class A:
    def filter_bunnies(self, pets):
        print('bunnies')

>>> getattr(A(), 'filter_bunnies')(1)
bunnies
like image 57
SilentGhost Avatar answered Sep 24 '22 21:09

SilentGhost


Yes, you can use:

globals()['filter_bunnies']()

to call 'filter_bunnies'.

like image 39
Olivier Verdier Avatar answered Sep 23 '22 21:09

Olivier Verdier