Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I give a function meta-data using decorators?

Based on this thread , I have the following

import functools
def predicate(author, version, **others):
    def _predicate(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            func.meta = {
                'author':  author,
                'version': version
            }
            func.meta.update(others)
            func(*args, **kwargs)
        return wrapper
    return _predicate

but I am unable to get the simple use case of

@predicate('some author', 'some version')
def second_of_two(a, b):
    return b

to work as expected:

>>> second_of_two.meta['author']
'some author'
>>> second_of_two(1, 2)
2

What am I doing wrong here?

like image 353
Sean Allred Avatar asked Oct 26 '25 09:10

Sean Allred


1 Answers

well, I don't see why you're using the functools stuff over here, whereas you need to make it a simple decorator with arguments:

def predicate(author, version, **others):
    def _predicate(func):
        func.meta = {
            'author':  author,
            'version': version
        }
        func.meta.update(others)
        return func
    return _predicate

@predicate('foo', 'bar')
def myfunc(i,j):
    return i+j

print myfunc.meta
print myfunc(1,2)

gives:

{'version': 'bar', 'author': 'foo'}
3
like image 59
zmo Avatar answered Oct 28 '25 21:10

zmo