Stephen Lu
Stephen Lu

Reputation: 314

Using a decorator to inject a function in Python

import functools
import logging
def logDeprecated( msg=None, *args, **kwargs ):
    """Log a message at level 'WARNING'

    Args:
        msg=None : (str)
            The message you wish to log.
            If no msg is passed, default to 'This function has been deprecated.'
            All other args are passed directly to logging.Logger.log().

    Keyword Args:
        category : (str)
            The category for the message to be logged.  If not
            specified, then an appropriate category will be
            determined based on the calling context.

        All other keyword args are passed directly to logging.Logger.log().

    Raises:
        n/a

    Returns:
        n/a

    """
    if not msg:
        msg = "This function has been deprecated."

    # Make sure category is stripped from kwargs before passing to log().
    cat = kwargs.pop('category', None)
    if not cat:
        cat = _getLoggingCategory()
    cat = "{0}.DEPRECATED".format(cat)

    logging.getLogger( category=cat ).log( logging.WARNING, msg, *args, **kwargs )

def decoratedLogDeprecated(func):
    def thisFunc(*args, **kwargs):
        func(*args, **kwargs)
        logDeprecated()
    return wraps(func)(thisFunc)

@decoratedLogDeprecated
def somefunc():
    print "This used to work"

def main():
    somefunc()

if __name__ == 'main':
    main()

The line number that is getting logged is the line number in main. When in actuality, it should be reporting the line number in the actual function.

Is there any way to use a decorator to inject that function into the decorated function? All the help would be greatly appreciated.

Upvotes: 3

Views: 1552

Answers (1)

Yevgen Yampolskiy
Yevgen Yampolskiy

Reputation: 7198

Here is how you can get both definition line number and call line number

from functools import wraps
def decoratedLogDeprecated(func):
    import inspect
    l = inspect.stack(1)[1][2]
    def thisFunc(*args, **kwargs):
        print "Defined at line", l
        func(*args, **kwargs)
        logDeprecated()

    return wraps(func)(thisFunc)

def logDeprecated():
    import inspect
    print "Called at line", inspect.stack(2)[2][2]

@decoratedLogDeprecated
def f():
    pass

@decoratedLogDeprecated
def g():
    pass

f()
g()

Upvotes: 4

Related Questions