2

I am trying to use the following decorator on functions defined in or imported to iPython notebook:

import warnings

def deprecated(func):
    '''This is a decorator which can be used to mark functions
    as deprecated. It will result in a warning being emitted
    when the function is used.'''
    def new_func(*args, **kwargs):
        warnings.warn("Call to deprecated function {}.".format(func.__name__),
                  category=DeprecationWarning)
        return func(*args, **kwargs)
    new_func.__name__ = func.__name__
    new_func.__doc__ = func.__doc__
    new_func.__dict__.update(func.__dict__)
    return new_func

I defined the decorator in utils.py. When I use the decorator this way:

import utils #from utils import deprecated

@utils.deprecated
def test():
    print 'Brokolice'

Then running test() prints 'Brokolice', but does not give any warning. However, when I define the decorator within iPython, I get the desired deprecated warning.

I am using Python 2.7 and I am not yet very comfortable with decorators or Python in general, but in this case, I have no idea what is wrong, as I would expect some kind of error if import of the decorator failed.

BoZenKhaa
  • 782
  • 1
  • 6
  • 22

2 Answers2

2

Try configuring warnings.filterwarnings('always') below the import warnings

In [1]: import test

In [2]: test.test()
warning
utils.py:12: DeprecationWarning: Call to deprecated function test.
  category=DeprecationWarning)
Brokolice
lapinkoira
  • 8,320
  • 9
  • 51
  • 94
  • Thank you, this works great! I was not expecting the problem to be with the 'warnings'. However, the warning now has a new line: `utils.py:69: DeprecationWarning: Call to deprecated function test. return func(*args, **kwargs)` , which is a line below the warning in the decorator. Any idea why is the line "return func(*args, **kwargs)" getting printed as well? :-) – BoZenKhaa Oct 23 '15 at 10:09
  • mmm I think you could configure the showwarning or formatwarning methods like it's suggested here http://stackoverflow.com/questions/2187269/python-print-only-the-message-on-warnings – lapinkoira Oct 23 '15 at 10:17
  • Ok, nice! Thank you very much! – BoZenKhaa Oct 23 '15 at 10:49
1
python -Wd test.py  #  -Wdefault

this will print the DeprecationWarning warnings which is hidden by python2.7 by default. see here for details.

And for your question "Any idea why is the line "return func(*args, **kwargs)" getting printed as well?".

This is just for readability..

length(line) should <= 80 in pep8

lhdgriver
  • 315
  • 1
  • 3
  • 17