Python dynamically creates function "Go"

Source: Internet
Author: User

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"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.