Python-dynamically call a function from a string

How to dynamically call a function from a string in Python

There were some explanations about dynamic calls to methods and properties, I didn't know how to dynamically call global functions and variables, so I looked it up.

eval() When you execute eval (), the string passed as an argument is evaluated as Python code. You can use it to call any function or variable value from a string.

Official documentation http://docs.python.jp/3.5/library/functions.html#eval

I use it like this

eval_test.py


def func():
    print('func() is called')

global_val = 'this is global'

#Normal global function, variable call
func()
print(global_val)

#Global functions and variable calls from strings
eval('func')()
print(eval('global_val'))

Execution result


$ python eval_test.py 
func() is called
this is global
func() is called
this is global

You can do anything with this

globals()

You can get the dictionary of functions and variables defined in the global scope by calling the built-in function globals ().

Official documentation http://docs.python.jp/3.5/library/functions.html#globals

I use it like this

function_call_test.py


def func():
    print('func() is called')
    #Globals in local scope()
    print(globals())

global_val = 'this is global'

#Globals in global scope()
print(globals())

#Normal global function, variable call
func()
print(global_val)

#Global functions and variable calls from strings
globals()['func']()
print(globals()['global_val'])

Execution result


$ python function_call_test.py 
{'global_val': 'this is global', '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10b185828>, '__name__': '__main__', '__package__': None, '__doc__': None, '__cached__': None, '__builtins__': <module 'builtins' (built-in)>, '__spec__': None, 'func': <function func at 0x10b186950>, '__file__': 'function_call_test.py'}
func() is called
{'global_val': 'this is global', '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10b185828>, '__name__': '__main__', '__package__': None, '__doc__': None, '__cached__': None, '__builtins__': <module 'builtins' (built-in)>, '__spec__': None, 'func': <function func at 0x10b186950>, '__file__': 'function_call_test.py'}
this is global
func() is called
{'global_val': 'this is global', '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10b185828>, '__name__': '__main__', '__package__': None, '__doc__': None, 'func_name': 'func', '__cached__': None, '__builtins__': <module 'builtins' (built-in)>, '__spec__': None, 'func': <function func at 0x10b186950>, '__file__': 'function_call_test.py'}
this is global

Both global functions and global variables can be called as strings. You can also see that the result of globals () is the same whether you call it from the global scope or from the local scope.

locals()

Unlike globals (), locals () can get the dictionary of functions and variables defined in the local scope.

Official documentation http://docs.python.jp/3.5/library/functions.html#locals

local_function_call_test.py


def func():
    def local_func():
        print('local_func() is called')

    print('func() is called')
    local_val = 'this is local'

    #Locals in local scope()
    print(locals())

    #Normal local function, variable call
    local_func()
    print(local_val)

    #Global functions and variable calls from strings
    locals()['local_func']()
    print(locals()['local_val'])


#Locals in global scope()
print(locals())
func()

Execution result


$ python local_function_call_test.py 
{'__name__': '__main__', '__spec__': None, '__cached__': None, '__doc__': None, '__builtins__': <module 'builtins' (built-in)>, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x1034bc208>, '__package__': None, 'func': <function func at 0x1034b2950>, '__file__': 'local_function_call_test.py'}
func() is called
{'local_val': 'this is local', 'local_func': <function func.<locals>.local_func at 0x10356c620>}
local_func() is called
this is local
local_func() is called
this is local

Both local functions and local variables can be called as strings. However, unlike globals (), you can see that the contents of locals () change depending on the block called.

(Reference) Dynamic invocation of classes, methods, and properties

It is summarized in the following article

・ Reflection in Python http://qiita.com/icoxfog417/items/bf04966d4e9706eb9e04

・ Introduction to black magic with Python http://www.slideshare.net/ssuser38b704/ll-lang-blackmagic

Summary

It seems that it can be used to check the functions and variables that are enabled in that scope. As far as I can see from the documentation, globals () seems to be statically determined

In the first place, I don't know if it will be necessary unless you are creating a framework etc ... Metaprogramming is abusive as it makes you confused

Recommended Posts

Python-dynamically call a function from a string
Call a Python function from p5.js.
How to create a function object from a string
How to call a function
[Python] How to call a c function from python (ctypes)
Create a pandas Dataframe from a string.
# 5 [python3] Extract characters from a character string
Generate a class from a string in Python
Call a command from Python (Windows version)
Call a Python script from Embedded Python in C ++ / C ++
Create a datetime object from a string in Python (Python 3.3)
[Go] How to write or call a function
dlopen () ltrace a function call in a shared library
[Python] I tried to get the type name as a string from the type function
Differentiate a two-variable function
# Function that returns the character code of a string
A note about __call__
Consider a conversion from a Python recursive function to a non-recursive function
Call Rust from Python to speed it up! PyO3 Tutorial: Wrapping a Simple Function Part ➁
Python> Read from a multi-line string instead of a file> io.StringIO ()
Call CPLEX from Python (DO cplex)
Create a function in Python
Write a kernel density function
Is this string a decimal?
Try creating a CRUD function
Let's draw a logistic function
What is a system call
What is a callback function?
Create an instance of a predefined class from a string in Python
[Road to Python Intermediate] Call a class instance like a function with __call__
[Introduction to Python] How to split a character string with the split function
How to get a string from a command line argument in python
Simple code to call a python program from Javascript on EC2
How to extract the desired character string from a line 4 commands
Call dlm from python to run a time-varying coefficient regression model