#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    26
    Rep Power
    0

    Dynamic function generation


    I have bunches of meta query definition like the one below. INSTTYPE, TRADETYPE etc. are attributes of my class object.

    OR[ (INSTType,'==','INTER'),
    ('TradeType','==','STD'),
    ('CCPTType','==','SWWR'),
    ('BookType','==', 'VTN'),
    ]

    I want to dynamically create and return a function based on the meta which is passed to me, the returned function will take in this meta description at runtime and evaluate it against my object returning True or False.

    this is a simple or expression of those attributes
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,905
    Rep Power
    481
    Are you looking for a transformation similar to that caused by this program concept?
    Code:
    print(eval('lambda x:x**3')(-2)) # proof of concept
    
    
    
    
    # function generation
    
    def make_a_dynamic_function(s = '''OR[(INSTType,'==','INTER'),
                                          ('TradeType','==','STD'),
                                          ('CCPTType','==','SWWR'),
                                          ('BookType','==', 'VTN'),
                                         ]'''):
    
        # processing of string s takes place
        
        # leading to
    
        return eval('''lambda o: (o.INSTType=='INTER') or (o.TradeType == 'STD') or (o.CCPTType=='SWWR') or (o.BookType == 'VIN')''')
    
    
    
    
    
    # use
    
    f = make_a_dynamic_function()
    
    f(my_object_with_all_those_attributes)
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    26
    Rep Power
    0

    Yes, something like that


    A closure with an inner function that handles each scenario. I return a particular inner function based on the meta description.

    Thanks
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,905
    Rep Power
    481

    closures are now a part of python


    Following program displays 15.
    Code:
    def f(x):
        def g(y):
            return x+y
        return g
    
    h = f(8)
    print(h(7))
    In old python releases you'd get the same effect using this trick which still works:
    Code:
    def f(x):
        def g(y, x=x):
            return x+y
        return g
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo