How to dynamically call a function in Python?

I would like to do something like:

dct = ['do_this', 'do_that']
dct[0]() // call do_this

But you cannot call the string as a function (get an error).

How can I achieve this without switching and without using a lambdas list or functions?

I want to pass a function by name.

+4
source share
9 answers

Functions are first class objects. So like this:

def do_this():
    print "In do_this"

def do_that():
    print "In do_that"

dct = [do_this, do_that]
dct[0]()

If you really want to call them from a list of strings, you can use globals ():

dct = ['do_this', 'do_that']
globals()[dct[0]]()

But I would suggest that using globals () (or locals ()) is probably not the right way to solve your problem. Grok python path:>>> import this

+10
source

Functions of first class objects in Python:

def do_this():
    pass

def do_that():
    pass

dct = [do_this, do_that]
dct[0]()  # calls do_this()

dct , eval():

eval(dct[0] + "()")

, globals() getattr() .

+12

getattr, globals(), :

dct = ['do_this', 'do_that']

getattr(my_module, dct[0])()

globals()[dct[0]]()
+3

dict


def fn_a():
    pass

some_dict = {
    'fn_a': fn_a,
}

class Someclass(object):

  @classmethod
  def fn_a(cls):
    pass

  # normal instance method
  def fn_b(self):
    pass

some_instance = Someclass()

: some_dict['name']() getattr(some_instance, 'fn_b')() getattr(Someclass, 'fn_a')()

+1

, , :

import module
getattr(module, funcname_string)(*args, **kwargs)
+1

, Python . , eval() ( ) globals(). , , . , .

+1
def do_this(): pass
def do_that(): pass

dct = dict((x.__name__, x) for x in [do_this, do_that])
# dct maps function names to the function objects
# the names *don't* have to match the function name in your source:
#   dct = {"foo": do_this}
# which means user-facing names can be anything you want

dct["do_this"]()  # call do_this
+1

getattrs()

dct = ['do_this', 'do_that']


getattr(class_object, dct[0])()

inspect.getmembers(my_class, predicate=inspect.ismethod)

for getattr(class, methodname)

, getattr , globals(). Globals() , .

0

To dynamically call a function defined in the same module, you can do this as follows:

import sys

## get the reference to the current module - key trick to get the ref to same module
this = sys.modules[__name__]

def foo():
  msg="I'm called dynamically!"
  return msg

## 'fname' can be taken as an input from the user
fname='foo'

## get the reference to the function from the module
fn = getattr(this, fname)

## make the function call
fn()
0
source

Source: https://habr.com/ru/post/1771381/


All Articles