There are similar problems on the understanding.
When a problem is encountered, the first thought is solved by dynamically creating a Python function, and the method of dynamically creating Python functions is investigated.
Defining a lambda function
Defining a lambda function in Python is simple,
Lambda " Foobar "
You can think of a lambda function as one of the most common ways.
Defining local functions
Functions in Python can be defined in code blocks, such as decorator, which is implemented in this way,
def Decorator (func): def _ (*args, * *Kwargs) :return func (*args, * *Kwargs) return _
Through types. Functiontype Creating a function
Types.functiontype in the Python standard library can also be used to create functions that are commonly used in the following two ways,
- Building a heart function from an existing function
def foobar (): return " Foobar " = types. Functiontype (foobar. __code__, {})
- Constructing with compile function
Module_code = Compile ('def foobar (): Return "Foobar" "exec ' forif= types. Functiontype (Function_code, {})print foobar ()
Create a function from an AST
In addition to compiling the string code directly through compile (), the AST-related objects can be created directly in Python, and eventually through compile (), types. Functiontype to build,
fromAstImport*ImportTypesfunction_ast=functiondef (Name='Foobar', args=arguments (args=[], Vararg=none, Kwarg=none, defaults=[]), Body=[return (Value=num (n=42, Lineno=1, col_offset=0), Lineno=1, col_offset=0)], decorator_list=[], Lineno=1, Col_offset=0) Module_ast= Module (body=[Function_ast]) Module_code= Compile (Module_ast,"<>","exec") Function_code= [C forCinchModule_code.co_constsifisinstance (c, types. CodeType)][0]foobar=types. Functiontype (Function_code, {})PrintFoobar ()
Create a function from eval
Finally there is an eval function,
Foobar = eval ('Lambda: ' Foobar')
You cannot define a function directly through DEF in the Eval function, so try to define a lambda function instead.
Other methods
In addition to some of the methods listed above, for example,
Write the function definition to a separate py file, and then import the module through the __import__ operation to get the defined function.
Summarize
The vast majority of applications with lambda or decorator are sufficient to meet demand, but the function of dynamic language is really want to engage in dynamic, but also can find a way.
Http://soliloquize.org/2015/07/02/Python: Several ways to dynamically create functions
Python dynamically creates function "Go"