True dynamic and anonymous functions possible in Python?

前端 未结 7 1410
说谎
说谎 2020-11-28 05:34

Just as a dynamic class can be created using type(name, base-classes, namespace-dict), can a dynamic function be created?

I\'ve tried doing something along the line

相关标签:
7条回答
  • 2020-11-28 06:04

    Yes. Use the def statement:

    def functor(f): # this dynamically creates a function at module load time
        def inner(g): #this dynamically creates a function on execution of functor
            return f(g)
    
        return inner
    

    Any solution involving freestanding text being compiled is equivalent to exec or eval, which leaves you with pre-existing functions and lexically captured data items to stitch together new functions. This might give you some ideas.

    0 讨论(0)
提交回复
热议问题